Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot open a bootstrap navbar on django
I'm asking this question in hopes that I ask it better this time. My bootstrap 4 navigation bar on my home page (Album template) does not click open and dsiplay links. Here is picture of what happens when I try to load this page in django. Those three lines cannot be clicked and opened. This is what should happen when those three lines are clicked. I've properly uploaded the boostrap album.min.css and the page loads and looks just like the original album example. I've also uploaded the stylesheet for this page. It looks exactly like the album example, except the navbar link cannot be clicked. Everything else works fine. My static files load. Here is the html file. {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../favicon.ico"> <title>Album example for Bootstrap</title> <link href="{% static 'css/album.min.css' %}" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'css/album.css' %}" rel="stylesheet"> <!-- jQuery (necessary for Bootstrap's JavaScript plugins)--> <script href="{% static 'js/jquery.js' %}" ></script> <!--jquery--> <!-- <script href = "{% static 'js/collapse.js' %}"></script> <script href = "{% static 'js/dropdown.js' %}"></script> --> </head> <body> <div class="collapse … -
Django - Hod do I request cURL from views
I am beginner to Django. I have cURL code, I want to run it from django views and get response. cURL code: curl -X POST \ -u "rzp_test_yourTestApiKey:yourTestApiSecret" \ --data "period=monthly" \ --data "interval=2" \ --data "item[name]=Test plan" \ --data "item[amount]=50000" \ --data "item[currency]=INR" \ https://api.razorpay.com/v1/plans Could someone please help me with this? or let me know if this doesn't make sense. Thanks. -
django login_required for variable urls
I am trying to write a basic website in django. I need the user (i'm still using the default one) to be able to login, logout, register, etc. I have the basic functionality set up, but I want the user to be able to visit a profile page where it will display basic information about the user. Naturally, the profile page must use the login_required decorator but the way I have it set up now is that once anybody signs in they can see any profile page. Part of the URL file: url(r'^profile/(?P<username>[\w.@+-]+)/$', login_required(ProfilePageView.as_view())), As you can see, the url should consist of "profile/" follow by the username of the user. How can I set it up so that only the user with the username following the "profile/" part of the url can see that page. With this code some user could login with any username and then just change the url and resend the get request. -
Django Image by Foreign Key and {% if / else %}
I trying to access the ImageField of a Model which is assigned via ForeignKey to another Model. I have different Animal Apps in my Projects, with almost the same structure, like the following models.py. On the landingpage of My Project I want to display the last 3 entry of every (Species) Models with Name and Picture. If the Species has no Picture I would like to display the ImageField of the Farm, which is connected via ForeignKey to my species. cows/models.py class Farm(models.Model): name = models.CharField(max_length=100) farm_img = models.ImageField(upload_to='farm_images/', max_length=255, null=True, blank=True) class Cows(models.Model): farm = models.ForeignKey(Farm, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100) entry_date = models.DateField(null=True, blank=True) cow_img = models.ImageField(upload_to='farm_images/', max_length=255, null=True, blank=True) Views.py class HomeIndex(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context['chickens'] = Chicken.objects.order_by('-entry_date')[:3] context['cows'] = Cows.objects.order_by('-entry_date')[:3] context['cats'] = Cats.objects.order_by('-entry_date')[:3] return context home.html <….> {% for somecow in cows %} <div class="col-3" id="p1"> <h2>{{ somecow.name }}</h2> <h2>{{ somecow.entry_date }}</h2> {% if somecow.cow_img %} <img src="{{ somecow.cow_img.url }}" alt="Mod" height="100"> {% endif %} </div> {% endfor %} <….> Until here it worked. But how can i access the FK.Model of the Model? Or in other Words how can I tell Django: “If you found no cow Picture in Cow.Model,then show a … -
rjust() inside __str__() not working in Django
I have a model class with level and name fields (it's about subcategories levels). I want to display the name of each row with corresponding number of dashes indent in the select dropdown in the admin panel. When I use: def __str__(self): return self.name.rjust((self.level-1) * 4, '-') in the Django model, it doesn't work and keeps showing me the name without the dashes. If I use the same code in a pure Python script, it does work. Debug showed that self.level has correct value in the __str__() Django function. Why it doesn't work in Django and how to fix it? -
Getting a error in django (self.model._meta.object_name django.contrib.auth.models.DoesNotExist: Group matching query does not exist.)
I want to realize the error for my site. I basically copied and pasted the following bits of code from the Django Project. I still get an Can somebody tell my what raised this error and how to fix it? Here is my error: I am Getting this error in django 2.0.5 and python 3. self.model._meta.object_name django.contrib.auth.models.DoesNotExist: Group matching query does not exist. I am getting this error specally on line number 14 views.py and line number 4 on context_processors.py. If you know the error pleasw help me i will be greatful to me. Here is my code: context_processors.py from django.contrib.auth.models import Group **def hasGroup(user, groupName): group = Group.objects.get(name=groupName) return True if group in user.groups.all() else False** def menu_processor(request): menu = {} user = request.user if hasGroup(user, 'doctor'): menu['Appointments'] = '/appointments' menu['Cases'] = '/case' elif hasGroup(user, 'patient'): menu['Reports'] = '/reports' menu['Appointments'] = '/appointments' menu['Medication'] = '/bill/medicines' menu['Bills'] = '/bill' menu['Cases'] = '/case' elif hasGroup(user, 'receptionist'): menu['New Patient'] = '/profile/register' menu['Manage Appointments'] = '/appointments' menu['New Appointment'] = '/appointments/book' menu['Bills'] = '/bill' menu['Cases'] = '/case' menu['Generate Case'] = '/case/generate' elif hasGroup(user, 'lab_attendant'): menu['Reports'] = '/reports' menu['Generate Report'] = '/reports/generate' elif hasGroup(user, 'inventory_manager'): menu['All Stock'] = '' menu['Stock Details'] = '' return {'menu': … -
How To display Subset Of Object In React Js
How To Display Subitem of Object I am able To Display Item But I can't display Subitem Here is attached the image I can't display comments section in Object I am using Django API and trying to display in react js And if You want some more details reagrding this i can share with you Please help Me Thanks import React, { Component } from 'react' import axios from 'axios'; import Iframe from 'react-iframe' import { Row ,Container,Col,Media } from 'react-bootstrap'; class Details extends Component { constructor(props) { super(props); this.state = { question: [], }; } async componentDidMount() { const { match: { params } } = this.props; const question = (await axios.get(`http://localhost:8000/api/movie/${params.pk}`)).data; console.log(question) this.setState({ question, }); } render() { const {question} = this.state; if (question === null) return <p>Loading ...</p>; return ( <Container className="de"> <Row> <Col sm={5} > <img className="card-img-top image" src={question.murl} alt="{{ post.name }}" style={{height: "480px"}} /> </Col> <Col sm={7} > <h1 className="name text-white">{ question.name }</h1> <p className="star" ><i className="fa fa-calendar df" ></i> { question.mdate } <span style={{marginLeft: "20px"}}><i className="fa fa-star-o df" ></i> { question.rating }/10 </span> <span style={{marginLeft: "20px"}}><i className="fa fa-clock-o df"></i> { question.movietime } </span></p> <p className="star" >{ question.mtype }</p> <h2 style={{color:"palegreen", fontFamily: "Segoe UI', Tahoma, … -
How can one create a custom "as_table()" method for forms?
I have a relatively complicated form that's used in multiple places on my website (in fact, it's a form from which many other form classes inherit). The inherited part of this form is always formatted identically—but that formatting is somehwat involved; each field is rendered and positioned manually in the template. This means that every template which displays this form has a lot of identical HTML markup that renders the form appropriately. I would like to create a custom output that can be called, similar to the as_table() methods. I'm aware that one can override the normal_row, error_row, etc. attributes—but the formatting of this form goes beyond that (for example, three of the form's five fields should be printed side-by-side, with a combined title). All of the tutorials/answered-questions I've seen either refer to overriding the above-mentioned attributes, or give instructions on how to manually render forms. Originally, I was thinking something like this: Class StrangeForm(form.Forms): .... def as_table_custom(): html_string = "\ <tr><td>Title 1:</td><td>self.fields['field1']</td><tr>\ <tr><td>Title 2:</td><td>self.fields['field2']</td><tr>\ <tr><td>Titles 3, 4, 5:</td><td>self.fields['field3']\ </td><td>self.fields['field4']</td><td>self.fields['field5']</td></tr>\ " return html_string But, after reading through the _html_output() and as_table() methods of Django's forms.py file, it doesn't look like it'll be that easy. If I write this from scratch, … -
Edit existing post in Django
in my project I have users write their stories. I would like them to have the ability to edit them as well. I use my NewStoryForm again, the one I used in order to create the story in the first place, from forms.py. Below I put my views .py and edit_story.html files. Thank you :) edit_story_view in views.py def edit_story_view(request, story_id): s = Story() if story_id is not None: story = get_object_or_404(Story, pk=story_id) else: story = Story() if request.method == 'GET': form = NewStoryForm(initial={'title': story.title, 'story': story.story}) else: form = NewStoryForm(data=request.POST) story.title = request.POST.get('title') story.story = request.POST.get('story') story.date = timezone.now() story.author = User.objects.get(id=request.user.id) story.save() return HttpResponseRedirect(reverse('pinkrubies:index', args=())) return render(request, "pinkrubies/edit_story.html", {'form': form}) edit_story.html {% extends "pinkrubies/base.html" %} {% block content %} <div class="post-preview"> <h2 class="post-title"> Edit your story </h2> </div> <form action="{% url 'pinkrubies:new_story' %}" method="post"> <div class="form-group"> <input type="text" id="title" name="title" class="form-control" placeholder="Title" value="{{ story.title }}" required/> </div> {% csrf_token %} <div class="form-group"> <textarea type="text" id="story" name="story" class="form-control" placeholder="Your story" rows="10" value="{{ story.story }}" required></textarea> </div> <button type="submit" class="btn btn-primary" style="float:right; background-color: #F2968A; border-color: #F2968A;">Save </button> </form> {% endblock %} -
Can I access static/admin/js/urlify.js on pythonanywhere.com?
I want to modify this file: http://.pythonanywhere.com/static/admin/js/urlify.js Specifically, to remove the stop words in: var removeList = []; I had no problem doing this on my local machine. On pythonanywhere I did the same thing to the two urlify.js files I could find: ~/.pythonanywhere.com/static/admin/js/urlify.js /home//.virtualenvs/.pythonanywhere.com/lib/python3.6/site-packages/django/contrib/admin/static/admin/js/urlify.js But the active file remains unchanged at: http://.pythonanywhere.com/static/admin/js/urlify.js Can I, in fact, access and edit my urlify.js file on pythonanywhere? -
Django - How do I display only the questions with choices?
I am completing the official Django tutorial. The tutorial involves creating a polls app, which consists of creating questions with choices. Currently, the index page shows one question instance for each choice that the question has. For example, if the question is 'what is your favourite thing to eat?' and that question's choices are 'Cabbage', 'Metal', and 'My pride', the index page shows three repetitions of 'what is your favourite thing to eat?'. I am trying to alter the index page to display only one instance of each question that has choices. How must I change what I have written already? views.py class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_questions' def get_queryset(self): """ Return the last ten published questions. Exclude questions to be published in the future and questions that have no choices. """ published_questions_with_choices = Question.objects.filter( choice__isnull=False).filter( pub_date__lte=timezone.now()) return published_questions_with_choices.order_by('-pub_date')[:10] index.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> {% if latest_questions %} <ul> {% for question in latest_questions %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} models.py class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text … -
Python Django Webapp is not responsive in smartphone
I have developed my first web app in python Django framework, deployed in pythonanywhere.com web server. I have already used the latest bootstrap in this app, but it is not responsive properly on a smartphone screen. responsive in laptop and tablet but not in a smartphone. You can also check it in your phone "http://sandeepbhatt.pythonanywhere.com/". please look into my base.html and index.html code, where is the problem, also please let me know if there are any details required to figure out this problem which is not mention in this post. My base.html code: <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script> <title>PIV</title> <!-- <link rel="stylesheet" href="{% static "css/index.css" %}"> --> </head> <body> <!-- <style> body{ background: url("{% static "images/background.jpg" %}"); background-size: cover; background-repeat: no-repeat;} </style> --> <!-- Navbar start from here --> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <!-- <a class="navbar-brand" href="">Navbar</a> --> <!-- Just an image --> <nav class="navbar navbar-light bg-light"> <a class="navbar-brand" href="{% url 'index' %}"> <img src="{% static " images/logo.jpg" %}" width="70" height="50" alt=""> </a> </nav> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> … -
I have .json file on my local machine. how can I create a quiz in django using that data. I am using mysql=5.7 version for dtabase
the json data is in format [ { "question": "Vertices of a quadrilateral ABCD are A(0, 0), B(4, 5), C(9, 9) and D(5, 4). What is the shape of the quadrilateral?", "optionA": "Square", "optionB": "Rectangle but not a square", "optionC": "Rhombus", "optionD": "Parallelogram but not a rhombus", "correct": "C" }, { "question": "What is the area of an obtuse angled triangle whose two sides are 8 and 12 and the angle included between the two sides is 150o?", "optionA": "24 sq units", "optionB": "48 sq units", "optionC": "243\u2013v243", "optionD": "483\u2013v483", "correct": "A" }, -
Django refering html path to another directory
I am new to Django. Just studying to render HTML pages in my app. I have an app directory named myapp. In that directory itself, I have created a hello.html. It is a simple HTML file. My view function is, def hello(request): today = datetime.datetime.now().date() return render(request, "hello.html", {"today" : today}) When I run my page, I got the following error. django.template.loaders.app_directories.Loader: /home/user/anaconda3/lib/python3.7/site-packages/django/contrib/admin/templates/hello.html (Source does not exist) I know it is referred from the wrong path. But Why it set to anaconda directory? I hope I have to change some settings? what are they? -
Django templating; queryset empty
I have a list of countries they all have there own url www.example.com/al/ for example. There is list of cities every country but the object_list is empty My View class CityOverview(generic.ListView): template_name = 'shisha/pages/country_index.html' model = City def get_queryset(self, *args, **kwargs): country_id = self.kwargs.get('country_id') return City.objects.filter(country__name=country_id) My Model class Country(models.Model): COUNTRY_CHOICES = ( ('al', 'Albania'), ('ad', 'Andorra'), #etc. etc. ) name = models.CharField(max_length=255, choices=COUNTRY_CHOICES, default='nl') def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=250) def __str__(self): return self.name My Urls path('<str:country_id>', views.CityOverview.as_view(), name='country'), My Template {% for city in object_list %} {{ city.name }} {% endfor %} This returns nothing and when i do {{ object_list }} It returns this <QuerySet []> Does anyone know what the problem is? -
How to set the initial value for different relationship fields in Django's admin
Summary We would like to set the initial selection of the select-boxes representing different kinds of model relationships on a basic "add" or "change" page in the Django admin. The initial selection should be saved to the database, if the user clicks one of the "Save" buttons. We specifically want to do this by setting the initial value on the form fields (for ModelAdmin or TabularInline). The question is: What is the proper "value" to assign to Field.initial, for different kinds of relationship form-fields? Background Suppose we have a simple Model with one or more relationship fields, i.e. OneToOneField, ForeignKey, or ManyToManyField. By default, the latter has an implicit through model, but it may also use an explicit through model, as explained in the docs. An explicit through model is a model with at least two ForeignKey fields. The relationship fields, represented by select-boxes, appear automatically on the standard ModelAdmin "add" or "change" forms, except for the ManyToManyField with explicit through model. That one requires an inline, such as the TabularInline, as explained here in the docs. Goal Now consider a basic Django ModelAdmin "add" (or "change") page for this model, including inlines for any explicit through models. We want … -
Django - CSS not showing
I am having troubles loading my CSS files in for a Django Project. The HTML templates display fine, but no CSS is applied. I have included snippets of the files below. Any suggestions are appreciated. Thanks base.html <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>My Site</title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> ... index.html {% extends "base.html" %} {% load static %} {% block body_block %} <h1>Homepage</h1> {% endblock %} settings.py ... STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR, 'static')] ... project tree projectName | appOne | | templates | | | appOne | | | | index.html | appTwo | projectName | | settings.py | static | | css | | | style.css | templates | | base.html -
In a template, how to create if statement when model.value == "str"
In my detail.html template i'm trying to create 2 separate views depending if the books genre is either fiction or nonfiction. How do i create the if statement for this in this scenario {% if genre == Fiction %} {% for x in book %} <h1>{{x.title}}: </h1> {% endfor %} {% else %} <h1> This is the other sections</h1> {% endif %} My book model has a value of "genre" that takes a string. How to i access this in the "if" statement in my templates? -
Django forms - best practice to set initial values in __init__() method
Sorry if this is a broad question, but I am trying to understand the best practice way to set initial values, edit fields (make readonly for E.g) in a django form init() method. Take my form for instance: class ResultForm(forms.ModelForm): evidence = forms.CharField( widget=forms.Textarea(attrs={'rows': 3, 'cols': 60}), label='Evidence:', required=False, ) def __init__(self, *args, **kwargs): super(ResultForm, self).__init__(*args, **kwargs) result_obj = self.instance if result_obj.tier_id: self.fields['evidence'].widget.attrs['readonly'] = True self.fields['evidence'].widget.attrs['class'] = 'classified' else: ... do stuff ... self.initial['evidence'] = new_evidence_variable class Meta: model = Result fields = ( 'id', 'evidence', 'tier_id', ) This is fine to render the unbound form, however when I attempt to validate it with POST data, the init method is run without a proper instance, and it fails. My way around this, is putting my code in init in a try/except block: class ResultForm(forms.ModelForm): evidence = forms.CharField( widget=forms.Textarea(attrs={'rows': 3, 'cols': 60}), label='Evidence:', required=False, ) def __init__(self, *args, **kwargs): super(ResultForm, self).__init__(*args, **kwargs) try: result_obj = self.instance if result_obj.tier_id: self.fields['evidence'].widget.attrs['readonly'] = True self.fields['evidence'].widget.attrs['class'] = 'classified' else: ... do stuff ... self.initial['evidence'] = new_evidence_variable except: pass class Meta: model = Result fields = ( 'id', 'evidence', 'tier_id', ) This seems to work, however it seems a little hacky. Is there a 'better' or … -
How to resume Scrapy spider where it left off?
I have a very large website with lots of URLs I would like to spider. Is there a way to tell Scrapy to ignore a list of URLs? Right now I store all the URLs in a DB column, I would like to be able to restart the spider but pass the long list (24k rows) to Scrapy so it knows to skip the ones it has already seen. Is there anyway to do this? -
Changing values in two models using one form - did not work. Django
I am trying to make changes in two models at the same time. So, according to one topic on the forum, I created two forms in one view and added it to one html. I think I am doing something wrong in my second form. Why my value in my model does not change to False? It looks more or less like that. views.pl if request.method == 'POST' and 'btn_massage_order' in request.POST: ordering_form = OrderingMassageForm(data=request.POST) if ordering_form.is_valid(): ordering = ordering_form.save(commit=False) massage_product = query_product # nazwa produkty masseurs = query_user # massage massage_time_interval = time # time example 60 min price_massage = price # price day_week = clean_my_date # day week time_compartment = ordering_form.cleaned_data['time'] [...] ordering.massage_product = massage_product ordering.masseurs = masseurs ordering.massage_time_interval = massage_time_interval ordering.time_compartment = time_compartment ordering.price = price_massage ordering.day_week = day_week [...] ordering.save() else: ordering_form = OrderingMassageForm() #next form i views if request.method == 'POST' and 'btn_massage_order' in request.POST: ordering_form = OrderingMassageForm(data=request.POST) ordering_form_on_off = TimeOnTimeOff(data=request.POST) if ordering_form_on_off.is_valid() and ordering_form.is_valid(): ordering_form_on_off = ordering_form_on_off.save(commit=False) # the value that will be save reservation = False # I receive my object time_compartment = ordering_form.cleaned_data['time'] # assigning my object ordering_form_on_off.time_compartment = reservation #save ordering_form_on_off.save() else: ordering_form_on_off = TimeOnTimeOff() forms.py class OrderingMassageForm(forms.ModelForm): class Meta: model … -
what is the correct way to include a script in html
I am currently working on a project using Django, and I am having a weird problem with my script tags. I have a layout.html file in which I have included Jquery and Bootstrap in the head. Using jinja, I am extending layout.html for my new file, main.html. In my new file I am now including a new script because this script is peculiar to this page. The problem I am having is that this new script does not work in main.html unless I again include Jquery in inside main.html. Please, I would like to know if there is an explanation for this? or maybe I am missing something? layout.html file <html> <head> // script to include jquery here, version 3.3.1 // other scripts include, bootstrap.js, popper.js, knockout.js </head> <body> { block content % } { % endblock % } </body> </html> Sample of main.html main.html { % extends "layout.html" %} {% block content %} // This new script below only works if jquery is included here // new script here <div> </div> {% endblock %} I am also using knockout.js, from which I am calling functions in new script on document load. The new script requires Jquery, But I don't … -
Why is Django adding a typo when saving a file?
I am writing some test code for a project I am making with Django. The test code is such: from django.test import TestCase, override_settings from django.core.files import File import sys import os from .models import Manual @override_settings(MEDIA_ROOT=os.getcwd()+'/temp/django_test') # Create your tests here. class ManualModelTests(TestCase): def tearDown(self): try: os.remove('/temp/django_test/test_image.jpg') except FileNotFoundError: pass def test_normal_manual_upload(self): in_image = open(os.path.join(os.path.dirname(__file__), 'test_image.jpg'), 'r+b') in_file = open(os.path.join(os.path.dirname(__file__), 'test_manual.pdf'), 'r+b') thumbnail = File(in_image) in_manual = File(in_file) new_manual = Manual.objects.create( photo=thumbnail, manual=in_manual, make='yoshimura', model='001', year_min=2007, year_max=2010 ) self.assertTrue(os.path.exists('/temp/django_test/photos/test_image.jpg')) self.assertTrue(os.path.exists ('/temp/django_test/manuals/test_manual.pdf')) self.tearDown() The model code is such: class Manual(models.Model): photo = models.ImageField(upload_to="photos") make = models.CharField(max_length=50) model = models.CharField(max_length=100) manual = models.FileField(upload_to="manuals") year_min = models.PositiveIntegerField(default=0) year_max = models.PositiveIntegerField(default=0) The test code aims to create a Manual object (just testing to see if the model saves normally). Upon running the code however, after finishing the model constructor call, I get a crazy long error that seems come after many calls of python's makdirs() function ends with OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Users\\Jason\\Projects\\motomanuals\\temp\\django_test\\photos\\C:' My guess is the problems stems from the path ending in '\\C:'? My questions are: Is my guess right. If not, then why am I getting this error? Why is Django … -
What is block usertools in django?
Following is code snippet from login.html {% block usertools %}<p style = "color:white ; margin-top: 20px; font-size: 8px;">{{ site_version|default:_('v1.0.0') }}</p>{% endblock %} i cant figure out what is significance of block usertools ? Is there any documentation for same. I cant see this block in base_site.html although. enter code here -
Filter Django object with another object
Django 1.11. I have a model Article, and another model ReadArticles. class Article(models.Model): name = models.CharField() length = models.IntegerField() class ReadArticle(models.Model): user = models.ForeignKey(User) article = models.ForeignKey(Article) I want to get a list of all articles which have not been read. I am already using Q: length_filter = Q(length__lt=5000) unread_articles = Article.objects.filter(length_filter).all() How to I extend this to exclude all articles whose ID/User combination are in the read_articles table?