Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset optimization with prefetch_related
I'm working on a project based on Django 1.11, and I'm trying to optimize database access with prefetch_related, here is what I'm facing: I have some model definitions(simplified): class D(models.Model): foo = models.IntegerField() class A(models.Model): foo = models.FloatField() class B(models.Model): a = models.ForeignKey(A) d = models.ForeignKey(D, related_name='bs') # Some fields are identical to C foo = models.CharField() # A special field bar1 = models.FileField() class C(models.Model): a = models.ForeignKey(A) d = models.ForeignKey(D, related_name='cs') # Some fields are identical to B foo = models.CharField() # A special field bar2 = models.FloatField() I want to retrieve some objects of D, when retrieving them from DB, I want to retrieve them along with all related(directly) B objects and C objects and related(indirectly) A objects, Currently I'm using: >>> qs = D.objects.filter(foo=1) # some queryset of D >>> qs = qs.prefetch_related('bs__a', 'cs__a') The performance is ok(compared with no prefetch_related), I see raw SQL queries from django-debug-toolbar and it looks like Django breaks the query into something like(psuedo SQL): select * from D select * from B where `d`.`id` in (ids from D) select * from A where `A`.`id` in (ids from B) ---> first time select * from C where `d`.`id` in (ids from … -
Django: m2m select with thumbnails
I am new to Django development and trying to build my own site with a portfolio of my work and a blog. The portfolio part of my site has posts that include a variable number of images to use as thumbnails. In Django admin, I would like to be able to see thumbnails of each image in the select form. Django's filter_horizontal is very close to what I am looking for, but it can't display thumbnails of the images Anyway, the models involved look something like this: class Image(models.Model): original = models.ImageField(upload_to='images') medium = ... thumbnail = ... class Project(models.Model): title = models.CharField(max_length=100) images = models.ManyToManyField(Image, blank=True) description = RichTextField(max_length=1000) content = RichTextField() This is a mockup of what I am trying to achieve. I've been reading through the documentation on Forms, ModelForms, and Widgets, but I am not entirely sure how to piece it all together or if I'm looking at the wrong thing entirely. Any help would be much appreciated, even if it's just pointing me in the right direction. -
Customize the nested data in Serializer
I have a ModelSerializer: class WorkOrderRetrieveSerializer(ModelSerializer): workordercomments = WorkOrderCommentForWorkOrderSerializer(many=True, read_only=True) class Meta: model = WorkOrder fields = "__all__" The JSON data is bellow: { "id": 1, "workordercomments": [ ..... { "id": 21, "content": "test files", "files": "[71]", "ctime": "2018-01-11T11:03:17.874268+08:00", "uptime": "2018-01-11T11:03:17.874362+08:00", "workorder": 1, "comment_user": { "id": 5, "username": "test03", "is_admin": true } } ], "workorder_num": "WON15118747168252", "name": "order01", "content": "first conntetn", "workordertype": "teck", "workorder_status": "created", "user_most_use_email": "lxas@128.com", "server_id": null, "public_ip": null, "belong_area": null, "files": null, "ctime": "2017-11-28T21:11:56.826971+08:00", "uptime": "2017-11-28T21:11:56.827064+08:00", "to_group": 3, "user": 2 } The "files": "[71]", in my JSON is a string of a group contains file ids. workordercomments is the related-name of the workorder. I want in the JSON workordercomments shows the files like this: { "id": 21, "content": "test files", "files": "['/media/images/xxxxx.png']", "ctime": "2018-01-11T11:03:17.874268+08:00", "uptime": "2018-01-11T11:03:17.874362+08:00", "workorder": 1, "comment_user": { "id": 5, "username": "test03", "is_admin": true } } The "files" value I want to is the link rather than its id. "files": "['/media/images/xxxxx.png']", or "files": ['/media/images/xxxxx.png'], Is it possible to customize the format? should I come true what function in serializer ? -
Pass data from Views.py to Forms.py
I am trying to move data from my views.py to my forms.py pages. I am using the FormWizard, however i dont think it will matter here. views.py def get_context_data(self, form, **kwargs): context = super(CheckoutWizard, self).get_context_data(form=form, **kwargs) kwargs = super(CheckoutWizard, self).get_form_kwargs() def get_form_kwargs(self): kwargs = super(CheckoutWizard, self).get_form_kwargs() kwargs.update({'first_name': 'james'}) kwargs.update({'last_name': 'bond'}) form = CreditCardForm(kwargs) return kwargs forms.py - in CreditCardForm def __init__(self, *args, **kwargs): for a in args: for key in a: print("key: %s , value: %s" % (key, a[key])) super(CreditCardForm, self).__init__(*args, **kwargs) In the forms file above I am accessing the data in *args with the nested loops because if i call args without the * i get this back ({'first_name': 'james', 'last_name': 'james'},) which i believe is a tuple with a dictionary in it. I have seen other solutions where other people are using **kwargs instead. My current solution feels a bit hacky so if there is a more correct or simpler way of doing this id appreciate the help. Its also strange to me that in views i am adding to kwargs, but then accessing that data in args. Any explanation on the differences would also be appreciated. Thanks! -
Django - adding checkout to django-carton
I've built a product app that utilizes django-carton, and I want to add 'checkout' functionality. I know the best route would be to use something like django-oscar, but in the spirit of finishing what I've started, and learning along the way I want to see if I can add checkout to this app. I'm looking for a starting point - since the checkout app will need to hand off for payment, and in some cases, deliver a link to a product. What is the best way forward for that? -
CSRF token missing or incorrect from form on `/`
I have this in urls.py: url("^$", direct_to_template, {"template": "index.html"}, name="home"), url("^searched-location", views.searched_location, name="searched_location"), I have this in index.html: {% extends "base.html" %} {% load pages_tags mezzanine_tags i18n staticfiles %} {% block main %} <form id="my-form class="input-group"> {% csrf_token %} <input type="text" class="form-control"> <script src="{% static "script/script.js" %}"></script> </form> {% endblock %} script.js has this line: document.getElementById("my-form").addEventListener("submit",function(event){ event.preventDefault(); },false); function when_User_Types_Something_Send_That_Stuff_To_The_Backend(typedStuff){ // some code $.post("/searched-location",{typed_stuff: stuff_the_user_typed}); } views.py has this: def searched_location(request): print request # More code here Problem is I'm getting this error in my terminal when I run python manage.py runserver locally: Forbidden (CSRF token missing or incorrect.): /searched-location [11/Jan/2018 01:57:06] "POST /searched-location HTTP/1.1" 403 2502 Why is the CSRF token missing or incorrect? How do I find or correct it? -
(1129, "Host 'IP is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts'")
Please do not mark as duplicate if possible. I do find out LOTS asking about this problem and all the results seem to be either flush hosts; or change the max_connect_errors variable to a higher value. But none of the posts are able to really have a reason of this. I am wondering are those the only two options? For me, this happened not right after but few days after I used galera to create few master to master mariadb replications. I had no idea why this is happening and it just happened randomly, even though I did try the flush hosts which worked perfectly each time, but it was still weird how this even happened. Does replication have something to do with this though? I did read some posts about crontab by the time when this error started to happen, I was researching how to make a bash to check maria db connection, cluster status and cluster size but haven't even done it yet. Today, I figured there is one way that this error will happen for sure, which is by going to django admin dashboard and go to one of my models. The first page only displays 100 … -
form.isValid() always return false in custom registration form django
I'm trying to make a custom user registration form in django but I can't understand why the method isValid() always return false please help me! forms.py class RegisterForm(UserCreationForm): class Meta: model = User fields = [ 'email', 'first_name', 'last_name', 'gender', 'birth_date', 'country', ] labels = { 'email':'Correo Electrónico', 'first_name':'Nombre', 'last_name':'Apellido', 'gender':'Sexo', 'birth_date':'Fecha de Nacimiento', 'country':'País' } widgets = { 'birth_date' : forms.SelectDateWidget(years=range(1930,2010)), 'gender' : forms.RadioSelect(), 'country' : CountrySelectWidget() } This is my views.py This is my register.html -
Djanjo dlib integration - pip install dlib have errors on macos 10.13.1
I am trying to install dlib library for my django project on my mac (macos 10.13.1), however i have this failure. I am using pip install dlib the last line had failed with error code 1 in /private/var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-build-m4fk5wp2/dlib/ below is the full execution with error $ pip install dlib Collecting dlib Downloading dlib-19.8.1.tar.gz (2.7MB) 100% |████████████████████████████████| 2.7MB 40kB/s Installing collected packages: dlib Running setup.py install for dlib ... error Complete output from command /Users/axilaris/Documents/project/somedotcom/somedotcomenv/bin/python3 -u -c "import setuptools, tokenize;__file__='/private/var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-build-m4fk5wp2/dlib/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-k_j5yu44-record/install-record.txt --single-version-externally-managed --compile --install-headers /Users/axilaris/Documents/project/somedotcom/somedotcomenv/include/site/python3.6/dlib: Warning: Functions that return numpy arrays need Numpy (>= v1.5.1) installed! You can install numpy and then run this setup again: $ pip install numpy running install running build Detected Python architecture: 64bit Detected platform: darwin Configuring cmake ... -- The C compiler identification is AppleClang 8.1.0.8020042 -- The CXX compiler identification is AppleClang 8.1.0.8020042 -- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Detecting C compile features -- Detecting C compile features - done -- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- Check for working CXX … -
How do I make my nginx load all static files from django docker app over HTTPS?
I have my nginx installed on the server and I have my Django application running inside a docker container. While my app loads fine over HTTP, it doesn't load any static files (CSS) over HTTPS. What changes should I make in nginx conf or docker app to solve this? -
Django templates inheritance looses original data
I'm learning django. I have a site with a data table that has the following html template: {% load static %} {% load table_tags %} <link href="{% static 'table/css/bootstrap.min.css' %}" rel="stylesheet"> <script src="{% static 'table/js/jquery.min.js' %}"></script> <script src="{% static 'table/js/bootstrap.min.js' %}"></script> <link href="{% static 'table/css/datatable.bootstrap.css' %}" rel="stylesheet"> <script src="{% static 'table/js/jquery.browser.min.js' %}"></script> <script src="{% static 'table/js/jquery.dataTables.min.js' %}"></script> <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Impala query metrics</title> </head> <body> <div class="container" style="margin: 10px 10px 10px"> <h1>Impala Query metrics</h1> <br /> {% render_table people %} </div> <a href="/logout">logout</a> {% block content %} {% endblock %} </body> When i try to inherit with another template by adding {% extends "base.html" %} to the first line, it inherits with base.html but my original data table disappears. Any help on how to keep my original data table or pointing me to the right documentation would be appreciated. -
Differences in import expressions?
I have a question regarding the import//from statement in python. In my views.py file (Project/App/views.py) I have this line: from django.views.generic import TemplateView, ListView Why do I have to include 'django' in that line? Why is it not enough to specify which directory (views) that the generic file is located in? This is what I have done in many of my previous python-only scripts - an example being: from random import foo as well as in my current django url.py file. There, I have: from app.views import view Why don't I have to specify that further, like with the first example where 'django' is included in the path-specification? How come I don't have to write it like this: from project.app.views import view Thank you! -
Django Admin Calander can't get reverse url to pull up next/previous month
I am getting an error on this reverse url call: extra_context['previous_month'] = reverse('admin:portal_event_changelist') + '?day__gte=' + str( previous_month) extra_context['next_month'] = reverse('admin:portal_event_changelist') + '?day__gte=' + str(next_month) -
Convert str to int in django template
I need to convert the a date day to int to compare with other value in the template. Something like this: views.py def userEdit(request): userdata = user.objects.get(id=request.session['user_id']) dic.update({'userdata':userdata, 'dayrange': range(1,32)}) return render(request, 'my_app/userEdit.html', dic) my_app/userEdit.html <select name="day"> {% for i in dayrange %} {% if i == userdata.birth_date|date:"d" %} <option value="{{ i }}" selected>{{ i }}</option> {% else %} <option value="{{ i }}">{{ i }}</option> {% endif %} {% endfor %} </select> I need to convert userdata.birth_date|date:"d" to int and then compare with the "i" variable in the for loop. Please help -
Connecting css, js, etc files to my Django rendered HTML webpage
I'm trying to render my HTML webpage and I'm having some issues. Here is my views.py file: from django.shortcuts import render def index(request): return render(request, 'index.html') Here is the TEMPLATES portion of my settings.py file: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['portfolio/PersonalSite', 'portfolio/PersonalSite/css/bootstrap.min.css', 'portfolio/PersonalSite/css/styles.css', 'portfolio/PersonalSite/js/scripts.min.js', 'portfolio/PersonalSite/files', 'portfolio/PersonalSite/libs/font-awesome/css/font-awesome.min.css', 'portfolio/PersonalSite/images/Guelph_Hacks_Logo.jpg', 'portfolio/PersonalSite/images/Tilt.jpg', ], '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', ], }, }, ] As you can see I tried to fix the problem by adding all the individual missing paths here but no luck unfortunately :( and here outputted error message: Django version 2.0.1, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [10/Jan/2018 16:54:41] "GET / HTTP/1.1" 200 10678 Not Found: /libs/font-awesome/css/font-awesome.min.css [10/Jan/2018 16:54:42] "GET /libs/font-awesome/css/font-awesome.min.css HTTP/1.1" 404 2178 Not Found: /css/styles.css [10/Jan/2018 16:54:42] "GET /css/styles.css HTTP/1.1" 404 2094 Not Found: /css/bootstrap.min.css [10/Jan/2018 16:54:42] "GET /css/bootstrap.min.css HTTP/1.1" 404 2115 Not Found: /images/Guelph_Hacks_Logo.jpg Not Found: /js/scripts.min.js [10/Jan/2018 16:54:42] "GET /images/Guelph_Hacks_Logo.jpg HTTP/1.1" 404 2136 [10/Jan/2018 16:54:42] "GET /js/scripts.min.js HTTP/1.1" 404 2103 Not Found: /images/Tilt.jpg [10/Jan/2018 16:54:42] "GET /images/Tilt.jpg HTTP/1.1" 404 2097 Not Found: /j_icon.jpeg [10/Jan/2018 16:54:42] "GET /j_icon.jpeg HTTP/1.1" 404 2085 If anyone could shed a little light on how I can properly fix this … -
Django error with encoding while I try to delete item from database
When I try to delete an item from the database I got the exception: The string that could not be encoded/decoded was: rm coöperat I attached screenshots with traceback and item: https://prnt.sc/hypxcc https://prnt.sc/hypyd4 -
How can I move data from views.py to a models.py in python/django in this case?
I put these files in the order the data travels. First the user submits a ticker via Charfield on the add file. Then the add function creates an instance of the score class by submitting the ticker value, which works. I also calculate points in add, but I can't figure out a way to send points to the class in models also. All of the examples I've seen on StackOverflow usually have variables in the class being related to some CharField or ForeignKey. So it possible to send points to score()? I also know scoreCalculate works. The error this code generates: File "~/models.py", line 6, in score points; NameError: name 'points' is not defined Of course it isn't defined, I'm just not sure what to define it as. add.html <form action="{% url 'add' %}" method="post"> {% csrf_token %} <label for="ticker">Ticker</label><br /> <input type="text" name="ticker" id="ticker"/> <br><br> <input type="submit" value="submit" /> </form> views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import score from Rssfeed import scoreCalculate def add(request): if(request.method == 'POST'): ticker = request.POST['ticker'] pts = scoreCalculate(ticker=ticker) sc = score(ticker = ticker) sc.save() return redirect('/') else: return render(request, 'add.html') models.py from django.db import models from datetime import … -
Regarding Debugging setup in pydev Django Mac
Can any body please shed some light on below error , i am trying to run django in a debug mode and Getting below error in eclipse Neon.3 Release (4.6.3) on MacOS, Python3 in virtual env setup. I have setup server properties in manage.py, i could also see space generated in ip and port http://127.0.0.1: 8082 pydevd.settrace('http://127.0.0.1', port='8082', stdoutToServer=True,stderrToServer=True) Any help would be highly appreciated. Many thanks, raky Error: warning: Debugger speedups using cython not found. Run '"/Users/XXX/Documents/YYYY/VirtualEnvironments/myVirtual1/bin/python3" "/Users/XXX/.p2/pool/plugins/org.python.pydev_6.2.0.201711281614/pysrc/setup_cython.py" build_ext --inplace' to build. pydev debugger: starting (pid: 4670) Could not connect to http://127.0.0.1: 8082 NoneType: None -
How do I paginate in django?
Here is the code of the views.py def view_images(request): return render_to_response('gallery/index.html',{ 'categories': Category.objects.all(), 'images': Image.objects.all(), 'video': Video.objects.all() }) I know its a messy way to code but I want to paginate this code -
Django Join three models
My model has these tables : class Stocks(models.Model): user=models.ForeignKey(User, null=True) name=models.CharField(max_length=128,verbose_name=_('stockname')) number=models.CharField(max_length=64,verbose_name=_('number')) suffix=models.CharField(max_length=12,verbose_name=_('uffix')) brand=models.CharField(max_length=64, ,verbose_name=_('brand')) class UserProfileInfo(models.Model): user=models.OneToOneField(User) tel = models.CharField(max_length=17,blank=True,verbose_name=_('tel')) address=models.CharField(max_length=264,verbose_name=_('address')) and thoe third table is default User model which has relation to UserProfileInfo and Stocks I have a table in Html like this : {% for item in allstocks %} <tr data-original-title="888" data-container="body" data-toggle="tooltip" data-placement="bottom" title="{{ ??? obj.address ??? }}"> <td>{{forloop.counter}}</td> <td>{{ item.user }}</td> <td>{{ item.name }}</td> <td>{{ item.brand }}</td> <td>{{ item.number }}</td> <td>{{ item.suffix }}</td> </tr> I think I should join those three tables to be able to show the address of the user in the mouseover tooltip of the HTML table, if so, How ? -
Ajax request to django view not returning response
I'm making a website where I want to load user submitted comments on elements and I want to be able to dynamically display them and not have the webpage have to load them all at once. so I setup this ajax request function: function loadcomments(){ $.ajax({ url: '/ajax/getcomments/', data: { 'identifier': {{ identifier }} 'begin': 0, 'end': 30 }, dataType: 'json', success: function (data) { alert(data.comments); } }); }; And a view to respond to that request: def obtain_comments(request, *args, **kwargs): begin = kwargs.get('begin'); end = kwargs.get('end'); comments = end - begin all_before = Comment.objects.order_by('-uploaded')[:end] data = { 'comments': all_before.order_by('uploaded')[:comments] } return JsonResponse(data) But I'm not getting a response. I'm not seeing any errors inside the browser console, however in the django runserver terminal I see: Internal Server Error: /ajax/getcomments/ Traceback (most recent call last): File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/trie/Desktop/django/vidmiotest/player/views.py", line 64, in obtain_comments comments = end - begin TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType' or if I set begin and end to a fixed value instead of kwargs: Internal … -
Why are there no images in my request.FILES (Django, Ajax)?
I try to get my images back after using an ajax call. Normally they should be in my request.FILES.getlist('images'). But they are not. When I print that out it shows 0. When I do alert(images.length); it is showing me that there are images before I do the ajax call. What I am doing wrong ? Thanks for your help. views.py @login_required def ajax_send_message(request): chatid = request.POST.get('chatid') chattext = request.POST.get('chattext') images = request.FILES.getlist('images') chat = Chat.objects.get(id=chatid) user = User.objects.get(id=request.user.id) message = Message(chat=chat, message=chattext, user=user) message.save() print(len(images)) data = {'chattext': chattext} return JsonResponse(data) chats.js $("#btn-send").click(function(){ var chatid = $(this).val(); var chattext = $("#chat-textarea").val(); var images = $('input#images').get(0).files; alert(images.length); var csrftoken = Cookies.get('csrftoken'); var formData = new FormData(); formData.append('chatid', chatid); formData.append('chattext', chattext); formData.append('images', images); formData.append('csrfmiddlewaretoken', csrftoken); $.ajax({ url:'/ajax/send_message/', data: formData, type: 'POST', cache: false, processData: false, contentType: false, dataType: 'json', success: function(){ showCurrentlySendMessage(chattext); } }); }); -
Running collectstatic on server : AttributeError: 'PosixPath' object has no attribute 'startswith'
After deploying on a server on digital ocean using nginx, gunicorn, django, and virtualenv, I try to use collectstatic: python manage.py collectstatic --settings=config.settings.production As you can see I have multiple setting files. One base, one local and one production setting file. Below is the error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 173, in handle if self.is_local_storage() and self.storage.location: File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/utils/functional.py", line 239, in inner return func(self._wrapped, *args) File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/tony/vp/vpenv/lib/python3.5/site-packages/django/core/files/storage.py", line 283, in location return abspathu(self.base_location) File "/home/tony/vp/vpenv/lib/python3.5/posixpath.py", line 357, in abspath if not isabs(path): File "/home/tony/vp/vpenv/lib/python3.5/posixpath.py", line 64, in isabs return s.startswith(sep) AttributeError: 'PosixPath' object has no attribute 'startswith' my production.py settings file contains the following: MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL ='media/' STATIC_ROOT = BASE_DIR / 'static' my base dir is as follows (imported from the base setting file): BASE_DIR = Path(file).resolve().parent.parent.parent What could be the cause? Thanks in advance! -
How to make a double Inner Join in django?
I have a django aplication that have to show the country name and the city name of a "need" in the list of candidate. To explain this better I have the next picture: So, here is the process: First, someone posts a "need" with their respective country and city. The city and the country are in diferent model. Then, the candidate can make an offer to resolve that need. I want to see in a list, all the offers I send to the need (just 1 offer to 1 need) but in my html template I want to display the name of the country and the city of the need. Here is my models.py class requiter (models.Model): requiter_name = models.CharField(max_length=200, null=True) class country (models.Model): country_name = models.CharField(max_length=200, null=True) class city (models.Model): city_name = models.CharField(max_length=200, null=True) class candidate (models.Model): full_name=models.CharField(max_length=230, null=True) class need(models.Model): requiter = models.ForeignKey(requiter, on_delete=models.CASCADE, null=True) title= models.CharField(max_length=300, null=True) description=models.TextField(null=True) country=models.ForeignKey(country, on_delete=models.CASCADE, null=True) city=models.ForeignKey(city, on_delete=models.CASCADE, null=True) class offer(models.Model): need = models.ForeignKey(need, on_delete=models.CASCADE, null=True) candidate = models.ForeignKey(candidate, on_delete=models.CASCADE, null=True) and here is my views.py def candidateprofile(request): candata = candidate.objects.get(id=request.session['account_id']) #HERE IS WHERE I WANT TO TAKE ALL THE OFFERS THAT THE CANDIDATE MADE, AND THE NAME OF THE COUNTRY AND … -
Django widget tweaks popover won't move with content
I'm using django widget tweaks to render a form field that is required. It all works fine, if the field is blank, I see a cute little popover that says field is required and all that, but if I scroll the page (the form is a little big), the popover won't move with the form field. It'll stay put and that is not good. Here's my code: {% load widget_tweaks %} {{form.order_number.label}} {% render_field form.order_number required="true" %} Also, this is happening only on Firefox, not on Chrome. I'm on Firefox 57.0. Here's a screenshot to help. In Pic1, you'll see it is supposed to be where I like it without scrolling. In Pic2, it has gone way upwards to the top of the div when I scroll up. Could someone please explain why this is happening and how I can fix it?