Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to intall sympy in my pycharm and code in django
I'm using Pycharm 2019.2.3 with python 2.7. The problem is that i want to include sympy lib. on my project and run using django framework. i am searching but solution is not find.. can uh please help me? -
pipenv or virtualenv , which one is better to use?
I am really frustrated by choosing which one to build my django projects on... what are the cons and pros of each so that i can choose one. on one hand some websites suggest using virtualenv , while on the other hand on quora some people suggest to use pipenv , some people say pipenv is not what the official site claims to be good, while other sites say this is the best every way to build you'r django projects. could you please help me get out of this headache ? -
how to change list contains as user is typing?
I have input and datalist like this. <input list="BrandTitle" name="BrandTitle"> <datalist id="BrandTitle"> {% for item in brand_list %} <option value="{{item.Title}}"> {% endfor %} </datalist> Now I want when I type something I get this on the server-side and send it to SOAP web services. and make brand_list from webservice response. I want to change the brand_list as the user is typing! for example when user type 'a' list shows: 'Apple' 'Facebook' 'Amazon' and when type 'ap' shows : 'Apple' -
How to get the data from the views.py to postgresql as I want to create a seperate table for result I am working on a django-quiz app?
i'm trying to get the data from my views.py to the database. if the views.py code is this views.py from django.shortcuts import render from .models import Questions def home(request): choices = Questions.CAT_CHOICES print(choices) return render(request, 'quiz/home.html', {'choices':choices}) def questions(request , choice): print(choice) ques = Questions.objects.filter(catagory__exact = choice) return render(request, 'quiz/questions.html', {'ques':ques}) def result(request): print("result page") if request.method == 'POST': data = request.POST datas = dict(data) qid = [] qans = [] ans = [] score = 0 for key in datas: try: qid.append(int(key)) qans.append(datas[key][0]) except: print("Csrf") for q in qid: ans.append((Questions.objects.get(id = q)).answer) total = len(ans) for i in range(total): if ans[i] == qans[i]: score += 1 # print(qid) # print(qans) # print(ans) print(score) eff = (score/total)*100 return render(request, 'quiz/result.html', {'score':score, 'eff':eff, 'total':total}) def about(request): return render(request, 'quiz/about.html') def contact(request): return render(request, 'quiz/contact.html') models.py class Questions(models.Model): CAT_CHOICES = ( ('sports','Sports'), ('movies','Movies'), ('maths','Maths'), ('generalknowledge','GeneralKnowledge') ) question = models.CharField(max_length = 250) optiona = models.CharField(max_length = 100) optionb = models.CharField(max_length = 100) optionc = models.CharField(max_length = 100) optiond = models.CharField(max_length = 100) answer = models.CharField(max_length = 100) catagory = models.CharField(max_length=20, choices = CAT_CHOICES) class Meta: ordering = ('-catagory',) def __str__(self): return self.question results.html {% extends "base.html" %} {% block title%} Result {% endblock … -
MultiValueDictKeyError when getting data submitted in form with Ajax in Django
I am learning Django web development by doing. I just learned how to POST data in form via AJAX. Now I have problem getting the data results back. Below works well for the POST function def cat_select(request): cat_selected=[] if request.method=='POST': #raise MultiValueDictKeyError when GET in the browser due to vertical having multiple values cat_name=['l2','l3'] cat_selected=[request.POST[x].split(',') for x in cat_name] print(cat_selected) else: cat_name=['l2','l3'] cat_selected=[request.GET[x].split(',') for x in cat_name] cat_selected=get_result(["US"],cat_selected) print(cat_selected) return JsonResponse({'cat':cat_selected},safe=False) <form id="cat_select">{% csrf_token %} <input class="site" name="site" type="text"> <input class="l2" name="l2" id="l2" type="text" style="width:30%"> <input class="l3" name="l3" id="l3" type="text" style="width:50%"> <br> <button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="cat_submit">Submit</button> </form> <script type="text/javascript"> $(document).on('submit','#cat_select',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/cat_select', data:{ l2:$('#l2').val(), l3:$('#l3').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function(){ alert ("selected!") } }); }); </script> I tried adding below within $(document).on('submit','#cat_select',function(e){ ,but the console Printed Error $.ajax({ method:'GET', url:'/cat_select', success:function(data){ console.log(data); }, error:function(data){ console.log('Error!'); } }); Internal Server Error: /cat_select Traceback (most recent call last): File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ list_ = super().__getitem__(key) KeyError: 'l2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in … -
PDF.js giving CORS issue in first attempt but after doing hard refresh its working fine without any issue
PDF.js giving CORS issue in first attempt but after doing hard refresh its working fine without any issue -
FOREIGN KEY constraint failed on deleting objects
When I am going to delete product from my cart it gives me error FOREIGN KEY constraint failed class Cart(TimeStamp): user = models.ForeignKey('authentication.User', on_delete=models.CASCADE, related_name='user_carts', null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) sub_total_price = models.DecimalField(max_digits=100, decimal_places=2, blank=True, null=True) quantity = models.PositiveIntegerField(default=1) here is model first I thought the problem would be on_delete and I changed it to SET_NULL but it was useless and it did not work, I tried to delete all files from migrations folder it also did not solve my problem. here is views.py class CartUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView): queryset = Cart.objects.all() serializer_class = CartSerializer permission_classes = (IsOwnerOrAdmin,) lookup_field = 'id' def get_queryset(self): return Cart.objects.filter(user=self.request.user) in this view except Destroy all are working properly but I cannot delete the object. Any idea please? -
How to pre fill fields in a form when using django-bootstrap-modal-forms
I am using django-bootstrap-modal-forms and it works perfectly as in documentation when using fields form my model. Some of the fields are ForeignKeys and they are displayed properly for user to select a value from database table that is referenced by the key, but instead of that I need to put username of the current user. I tried to change how the CreateView class handles fields, but with no luck. Probably doing something wrong. models.py class userSchoolYear(models.Model): user_in_school = models.ForeignKey(get_user_model(), null=True, on_delete=models.CASCADE) school = models.ForeignKey(sifMusicSchool, on_delete=models.CASCADE) school_year = models.ForeignKey(sifSchoolYear, on_delete=models.CASCADE) school_year_grade = models.CharField(max_length=4, choices=IZBOR_RAZREDA, default=None, null=True) user_instrument = models.ForeignKey(instType, on_delete=models.CASCADE, default=None, null=True) user_profesor = models.ForeignKey(profSchool, on_delete=models.CASCADE, default=None, null=True) views.py class SchoolYearCreateView(BSModalCreateView): template_name = 'school_year.html' form_class = SchoolYearForm success_message = 'Success!' success_url = reverse_lazy('school') def __init__(self, *args, **kwargs): self.form_class.user_in_school = 'johnny' ### HERE print(user.username) super().__init__(*args, **kwargs) -
what is difference between raw sql queries & normal sql queries?
I am kind of new to sql and database & currently developing website in django framework. During my reading of django documentation I have read about raw sql queries which are executed using Manager.raw() like below. for p in Person.objects.raw('SELECT * FROM myapp_person'): Manager.raw(raw_query, params=None, translations=None) How does raw queries differes from normal sql queries & when should I use raw sql queries instead of Django ORM ? -
While installing ssh in terminal prompt getting below error, any solution is there for this issue
While installing ssh in terminal prompt getting below error, any solution is there for this issue :\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build>pip install pycrypto Collecting pycrypto Using cached https://files.pythonhosted.org/packages/60/db/645aa9af249f059cc3a368b118de33889219e0362141e75d4eaf6f80f163/pycrypto-2.6.1.tar.gz Installing collected packages: pycrypto Running setup.py install for pycrypto ... error ERROR: Command errored out with exit status 1: command: 'c:\users\surya\appdata\local\programs\python\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Surya\AppData\Local\Temp\pip-install-19mldbr_\pycrypto\setup.py'"'"'; file='"'"'C:\Users\Surya\AppData\Local\Temp\pip-install-19mldbr_\pycrypto\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\Surya\AppData\Local\Temp\pip-record-mvo6rvxc\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\Surya\AppData\Local\Temp\pip-install-19mldbr_\pycrypto Complete output (159 lines): running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\Crypto copying lib\Crypto\pct_warnings.py -> build\lib.win32-3.7\Crypto copying lib\Crypto_init_.py -> build\lib.win32-3.7\Crypto creating build\lib.win32-3.7\Crypto\Hash copying lib\Crypto\Hash\hashalgo.py -> build\lib.win32-3.7\Crypto\Hash copying lib\Crypto\Hash\HMAC.py -> build\lib.win32-3.7\Crypto\Hash copying lib\Crypto\Hash\MD2.py -> build\lib.win32-3.7\Crypto\Hash copying lib\Crypto\Hash\MD4.py -> build\lib.win32-3.7\Crypto\Hash copying lib\Crypto\Hash\MD5.py -> build\lib.win32-3.7\Crypto\Hash copying lib\Crypto\Hash\RIPEMD.py -> build\lib.win32-3.7\Crypto\Hash copying lib\Crypto\Hash\SHA.py -> build\lib.win32-3.7\Crypto\Hash copying lib\Crypto\Hash\SHA224.py -> build\lib.win32-3.7\Crypto\Hash copying lib\Crypto\Hash\SHA256.py -> build\lib.win32-3.7\Crypto\Hash copying lib\Crypto\Hash\SHA384.py -> build\lib.win32-3.7\Crypto\Hash copying lib\Crypto\Hash\SHA512.py -> build\lib.win32-3.7\Crypto\Hash copying lib\Crypto\Hash_init_.py -> build\lib.win32-3.7\Crypto\Hash creating build\lib.win32-3.7\Crypto\Cipher copying lib\Crypto\Cipher\AES.py -> build\lib.win32-3.7\Crypto\Cipher copying lib\Crypto\Cipher\ARC2.py -> build\lib.win32-3.7\Crypto\Cipher copying lib\Crypto\Cipher\ARC4.py -> build\lib.win32-3.7\Crypto\Cipher copying lib\Crypto\Cipher\blockalgo.py -> build\lib.win32-3.7\Crypto\Cipher copying lib\Crypto\Cipher\Blowfish.py -> build\lib.win32-3.7\Crypto\Cipher copying lib\Crypto\Cipher\CAST.py -> build\lib.win32-3.7\Crypto\Cipher copying lib\Crypto\Cipher\DES.py -> build\lib.win32-3.7\Crypto\Cipher copying lib\Crypto\Cipher\DES3.py -> build\lib.win32-3.7\Crypto\Cipher copying lib\Crypto\Cipher\PKCS1_OAEP.py -> build\lib.win32-3.7\Crypto\Cipher copying lib\Crypto\Cipher\PKCS1_v1_5.py -> build\lib.win32-3.7\Crypto\Cipher copying lib\Crypto\Cipher\XOR.py -> build\lib.win32-3.7\Crypto\Cipher copying lib\Crypto\Cipher_init_.py -> build\lib.win32-3.7\Crypto\Cipher creating build\lib.win32-3.7\Crypto\Util copying lib\Crypto\Util\asn1.py -> … -
When I write this command "python2 main.py" I get those problems
Traceback (most recent call last): File "main.py", line 122, in <module> driver = webdriver.Chrome() File "/usr/lib/python2.7/dist-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__ desired_capabilities=desired_capabilities) File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__ self.start_session(capabilities, browser_profile) File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/usr/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir -
I keep receiving ValueError on my Django Python Forum application
I'm trying to create a form where users can add a new topic within a category. Then the users will be able to comment on each topic. Everything was working up until I tried adding the form page for new_topic The error I receive: ValueError at /new_topic/ The view speak_space.views.new_topic didn't return an HttpResponse object. It returned None instead. Heres the code for my view.py and urls.py files: view.py from django.shortcuts import render, redirect from .models import Category from .models import Topic from .forms import TopicForm def index(request): """The home page for speak_space""" return render(request, 'speak_space/index.html') def categories(request): """Show all categories.""" categories = Category.objects.order_by('date_added') context = {'categories': categories} return render(request, 'speak_space/categories.html', context) def category(request, category_id): """Show a single category(tribe) and all of its topics(convos).""" category = Category.objects.get(id=category_id) topics = category.topic_set.order_by('-date_added') context = {'category': category, 'topics': topics} return render(request, 'speak_space/category.html', context) def topics(request): """Show all topics within a category(tribe).""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'speak_space/topics.html', context) def topic(request, topic_id): """Show a single topic(convo/post) and all of it's replies.""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'speak_space/topic.html', context) def new_topic(request): """Add a new conversation topic.""" if request.method != 'POST': # No … -
Using django-twilio package forgery protection is creating forbidden 403 error
I am using django-twilio package for forgery protection django-twilio forgery protection docs I have a django texting app that is being used to both send automated messages directly through my cellphone messenger and also from my website while logged in. When DJANGO_TWILIO_FORGERY_PROTECTION = False, both platforms using my django texting app work. When DJANGO_TWILIO_FORGERY_PROTECTION = True, only cellphone messenger works, and website gets 403 Forbidden. How can this be fixed while maintaining as much security as possible and keeping the same app as functional for both cellphone messenger and website. I know issue is to do with @twilio_view decorator send-text.html <form action="{% url 'text-send' %}" enctype="multipart/form-data" method="POST"> {% csrf_token %} <input type="text" name="Body" required> <input type="submit" > </form> Here is my texting app: @twilio_view def sendtext(request, reviewpk): if request.method == "POST": ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN client = Client(ACCOUNT_SID, AUTH_TOKEN) message_body = request.POST['Body'] client.messages.create( to= "+13231342344", from_="+14571342764", body=message_body ) return confirm_things(request) def confirm_things(request): if 'HTTP_X_TWILIO_SIGNATURE' in request.META: resp = MessagingResponse() resp.message("good job message was sent") return HttpResponse(str(resp), content_type='text/xml') return HttpResponseRedirect(reverse('dashboard')) urls.py urlpatterns = [ path('textsend/', views.sendtext, name='text-send'), path('dashboard/', views.dash, name='dash'), ] -
How to validate multiple user ids in m2m field
I have on models name 'company' and user model has foreign-key of 'company'. now I have one model name 'group' which is m2m with the user. I am getting a comma-separated id's of the user in request but now I have to check that those ids belong to the requested user's company if yes then pass else remove them. I have customized validate method in serializer it works but for that, I have to use for loop and make a query in models its kind of slowing down response. so I am looking for another alternative solution like how can i use this validation in permission (BasePermission) or somewhere else to avoid loop and queries. -
The view SugarNoter.views.Index didn't return an HttpResponse object. It returned None instead
Whenever a New user is going to register, after that I get this error. even I return HttpResponse The view SugarNoter.views.Index didn't return an HttpResponse object. It returned None instead. views.py def Index(request): if request.method=='POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') passwd = form.clean_password2() user = auth.authenticate(username=username, password=passwd) auth.login(request, user) return redirect(f'users/{str(request.user)}') else: context = { 'form':UserCreationForm() } return render(request, 'index.html', context) html file {% load crispy_forms_tags %} <div class="container"> <div class="col-sm-6 my-5 mx-auto"> <div class="card align-items-center justify-content-center"> <div class="card-body"> <form method="POST"> {% csrf_token %} {{ form | crispy }} <button type="button" class="btn btn-danger" onclick='window.location="login"'>Login</button> <button type="submit" class="btn btn-success">Sign Up</button> </form> </div> </div> </div> </div> What should I do? -
Unable to embed the image file in the template uploaded by user
I am trying to load the uploaded image in the template. The image is getting correctly uploaded and the url is also correct but I am still getting the 404 error. The error is:- Failed to load resource: the server responded with a status of 404 (Not Found) template {% if complaint.media %} <img src="{{ complaint.media.url }}" height="100px" width="100px" > {% endif %} settings.py MEDIA_DIR = os.path.join(BASE_DIR,'media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' models.py class Complaints(models.Model): media = models.ImageField(upload_to='complaints_image',blank=True) forms.py class ComplaintForm(forms.ModelForm): class Meta(): model = Complaint fields = ('department','heading','text','media',) -
django two foreignkey filtering
I already tried this to my views "fees = SchoolFeesMasterList.objects.filter(Education_Levels=studentenroll.Education_Levels)" and this "fees = SchoolFeesMasterList.objects.filter(Education_Levels=StudentsEnrollmentRecord.Education_Levels)" and none of them work. \\model class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,blank=True,null=True) Remarks = models.TextField(max_length=500,null=True,blank=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE,null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,blank=True) Courses= models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,null=True,blank=True) Sections= models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE,null=True) Subjects= models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE,null=True) Employee_Users= models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,null=True) Start_Date = models.DateField(null=True,blank=True) End_Date = models.DateField(null=True,blank=True) Remarks = models.TextField(max_length=500) def __str__(self): suser = '{0.Employee_Users}' return suser.format(self) \\views def enrollmentform(request): id = request.GET.get('StudentID') if StudentsEnrollmentRecord.objects.filter(Student_Users=id).exists(): studentenroll = StudentsEnrollmentRecord.objects.filter(Student_Users=id) FeesType = SchoolFeesMasterList.objects.filter(Education_Levels=StudentsEnrollmentRecord.Education_Levels) return render(request, 'Homepage/enrollmentrecords.html',{"studentenroll":studentenroll,"SchoolFeesType":FeesType}) else: . . . return render(request, 'Homepage/EnrollmentForm.html', {"students": students, "edulevel": edulevel, "payment": payment, 'sched': sched, 'subj': subj, "year": year, "doc": doc,"education":education,"payments":payments}) can you guys help me on how to filter the StudentsEnrollmentRecord(Education_Levels) to SubjectSectionTeacher(Education_Levels) because it is really hard to understand the django-filter, i waste already 2 days for this error. I just want to filter the SubjectSectionTeacher(Education_Levels) using StudentsEnrollmentRecord(Education_Levels) -
Sanitizing markdown using bleach
I'm using Django with markdown and bleach to sanitize markdown. Most xss tricks are filtered now using Bleach however, I can't find a way against this: <img src="" onerror=alert(/XSS/) /> or hello <a name="n" href="javascript:alert('xss')">*you*</a> Users can use things like: [Hello](javascript:alert\('xss'\)) What's the best way to sanitize this in Python/Django ? -
cannot install Django under virtualenv
when I type command :"pip install django", show error message: ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied when I try command :"pip install django --user",show error message: ERROR: Can not perform a '--user' install. User site-packages are not visible in this virtualenv. I want to install Django under virtualenv on my Mac ,but as the summarize show , my permission denied me , and I make sure I am the root user . (newVENV10112019) braveru@BraveRudeMacBook-Air bin % pip install django Collecting django Using cached https://files.pythonhosted.org/packages/b2/79/df0ffea7bf1e02c073c2633702c90f4384645c40a1dd09a308e02ef0c817/Django-2.2.6-py3-none-any.whl Collecting pytz (from django) Using cached https://files.pythonhosted.org/packages/e7/f9/f0b53f88060247251bf481fa6ea62cd0d25bf1b11a87888e53ce5b7c8ad2/pytz-2019.3-py2.py3-none-any.whl Collecting sqlparse (from django) Using cached https://files.pythonhosted.org/packages/ef/53/900f7d2a54557c6a37886585a91336520e5539e3ae2423ff1102daf4f3a7/sqlparse-0.3.0-py2.py3-none-any.whl Installing collected packages: pytz, sqlparse, django ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Users/braveru/CodingNow/VENV/newVENV10112019/lib/python3.7/site-packages/pytz' Consider using the --user option or check the permissions. (newVENV10112019) braveru@BraveRudeMacBook-Air bin % pip3 install django --user ERROR: Can not perform a '--user' install. User site-packages are not visible in this virtualenv. I try all the way that is search from google , and I also re-install my MacOS , the same will happen . -
How can I build a form like that ?? (I’m usine Django)
enter image description here I really don’t Know how to get something like that with django models -
My django not works properly, version 2, i can't understand?
my problem starts when i try to include my files with a extension .urls here the code: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('' include('hello_world.urls'), ] TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": ["personal_portfolio/templates/"], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request" "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ] }, } ] my admin.site.urls file: >> https://localhost.com my hello_world.urls file: >> <h1>hello world</h1> -
One model to have children and parents objects in Django
I am trying to create a tool that replicates the use of an EXCEL sheet. The ideal use is to have: -Sections (Parent objects) -Fields to be filled (Children objects of given section) Ideally, I am looking for this to be in one Model class called Car specifications (for example). A typical object of this would have a one-to-one relationship with model Car. Each Car Specification object would have Sections, e.g Car Headlights, and there are a number of fields to be filled for Car Headlights section (e.g type, size, manufacturer..etc). It can be text, date, file.. or even another model object(s). My question is: What would be the best way to approach this? I apologies if my terminology usage is wrong, I'm still a python-django beginner :) Thank you in advance! An example Excel sheet might look like this: 1.0 Car Headlights 1.1 Headlight type: 1.2 Headlight shape: 1.3 Compatible models: this is a list/one to multi relationship 2.0 Windows# 2.1 Glass type: 2.2 Country of origin: 2.3 Tint level: And so on -
Django model for table with foreign keys to multiple tables in one column
I have inherited a table that has data that has foreign keys to different tables that share a column. The dedupe_sig column is a virtual column with a uniqueness constraint where the place names are sorted. It's used to ensure that you don't try to store both Toledo S Ann Arbor and Ann Arbor N Toledo: the table with the directions says that S and N are opposites. location_type place1 relation place2 dedupe_sig --------------- ------------- ---------- -------------- ---------------------------------- city Youngstown SE Cleveland city Cleveland Youngstown neighborhood Campus S Clintonville neighborhood Campus Clintonville region Midwest NW The South region Midwest The South city Cincinnatti NE Lexington city Cincinnatti Lexington state Ohio E Indiana state Indiana Ohio state Illinois S Wisconsin state Illinois Wisconsin What I'd like to know is if there's a sane way for me to add this table to my Django models? It seems like it should be a ManyToManyField, but I'm not sure how to handle implementing it without changing the schemata (either by making separate join tables for the different location types or by moving all the location data into a single table that links to itself for arbitrary nesting hierarchy). -
Boolean condition doesn't work in django template
i'm trying to add in my template a simple "s" to a string depending on the number of answers : The house contains {{nb_results2}} {% if nb_results2 >= 2 %}rooms{% else %}room{% endif %} {{nb_results2}} appears in my page (it's a str of a count), but whatever the number is, only "room" is displayed. Is it something related to the string nature of my nb_results variable ? Thanks for your help ! -
How to delete a kwargs argument if it is empty?
I am working with arguments, variables that I go through GET and I receive in my view to do my queryset, the problem is, if I receive an empty argument does not work, I explain more with code. My url example: http://127.0.0.1:8000/my_view/?val1=xd&val2=lol&sox= My view.py val1 = request.GET.get('val1', None) val2 = request.GET.get('val2', None) foo = request.GET.get('lol', None) filters = { 'code_field': val1, 'tiempo_field__lte': val2, 'code_id__exact': foo, } my_query = Babies.object.filter(**filters) In this example sox is empty, that's why it doesn't work for me I think, what would be the elegant way if an argument comes empty is not taken in the query.