Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, error importing view from another app
I'm trying to import a view from one app to another in my project. When using this: from ..from ..KnownLocation.views import KnownLocationView I get the following error: ValueError: attempted relative import beyond top-level package When trying to use: from triangulationapi.KnownLocation.views import KnownLocationView It's raising the following error. ModuleNotFoundError: No module named 'triangulationapi.KnownLocation' my Project tree: ├── find_second_gdt │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── second_GDT_finding │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── __init__.py ├── KnownLocation │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py ├── requirements.txt. └── triangulationapi ├── asgi.py ├── __init__.py ├── __pycache__ ├── settings.py ├── urls.py └── wsgi.py And, what's the diffrence between using .. and project.app.view... I thought it is the same up until now. -
django on IIS winserver 2016 wfastcgi handler line 791
installed python 3.8.1 ,django 3.0.3 on windows server 2016 with wfastcgi and iam getting this error, cant find anything to fix it.. gave IIS AppPool\DefaultAppPool read&use permissions on python installation folder but it still does not work, somehow the handler can`t read it, but as much as i know the config seems to be right. Hope you can help me. Thanks in regards. C:\inetpub\wwwroot -> web.conf <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\users\administrator\python38\python.exe|c:\users\administrator\python38\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="web.wsgi.application" /> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\AddressLizenzbuch" /> <!-- Optional settings --> <add key="DJANGO_SETTINGS_MODULE" value="web.settings" /> </appSettings> </configuration> C:\inetpub\wwwroot\AddressLizenzbuch\web\blog\static -> web.config <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <!-- Overrides the FastCGI handler to let IIS serve the static files --> <handlers> <clear/> <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="File" requireAccess="Read" /> </handlers> </system.webServer> </configuration> manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'web.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ … -
Applying a list of items to every view in views.py
Is there a way to apply a list of items to every view without having to do it manually for every view? I have got a list of items in my navbar and I have to add this to every view to have it displayed in every page: category_list = Category.objects.all() context = { 'category_list': category_list } -
Multiple Django OneToOne ModelForm Validation in single Create View
I have three modelforms and I am trying to validate those forms in a single view. All forms are connected with OneToOne relation. I cannot validate subforms after main form ins same view. Tried few solutions and I guess I am doing something wrong and if someone can help I can redo it few times to understand it at my end. DoctorForm works fine but I couldn't find a suitable method to validate DoctorQualificationForm() and WorkExperienceForm(). Following is the code: Models: class User(AbstractUser): ACC_TYPE = ( ('', ''), ('Doctor', 'Doctor'), ('Patient', 'Patient') ) account_type = models.CharField(max_length=20, choices=ACC_TYPE, null=True, blank=True) cell_phone = models.IntegerField(null=True, blank=True) landline = models.IntegerField(null=True, blank=True) pic = models.ImageField(upload_to='profile/', null=True, blank=True) secondary_email = models.EmailField(null=True, blank=True) def __str__(self): return str(self.username) def get_absolute_url(self): return reverse('user:detail', kwargs={'pk':self.user.pk}) class Role(models.Model): LAB_ADMIN = 1 SALES_ADMIN = 2 SALES_EXCUTIVE = 3 LAB_TECH = 4 ROLE_CHOICES = ( (LAB_ADMIN, 'Lab Admin'), (SALES_ADMIN, 'Sales Admin'), (SALES_EXCUTIVE, 'Sales Executive'), (LAB_TECH, 'Lab Tech'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True) doctor = models.OneToOneField('Doctor', on_delete=models.CASCADE, related_name='roles') def __str__(self): return self.id class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='doctor', null=True) about = models.TextField() #role = models.OneToOneField(Role, on_delete=models.CASCADE, related_name='currentrole',null=True, blank=True) street = models.CharField(max_length=200) city = models.CharField(max_length=200) country = models.CharField(max_length=200) cell_phone = models.CharField(max_length=200) landline = models.CharField(max_length=200) … -
WHY DJANGO IS SHOWING ME THIS ERROR WHEN I TRY TO OPEN NEW PAGE WITH HYPERLINK
*URLS.PY* //URLS.PY FILE from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage, name='homepage'), path('login', views.login, name='login'), ] **VIEWS.PY** from django.http import HttpResponse from django.shortcuts import render def homepage(request): return render(request, 'bms_homepage_template/bms_homepage.html') def login(request): return render(request, 'bms_homepage_template/login_page.html') **login_page.html** <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login Page</title> </head> <body> <h1>LOGIN INTO YOUR ACCOUNT</h1> <form action=""> Account Number: <input type="text"> <br> Password: <input type="text"> <br> <input type="submit" value="submit"> </form> </body> </html> **bms_homepage.html** <a href="login_page.html"><button id="login">LOGIN</button></a> What i want to do is from homepage.html, when i click on login button it should open login_page.html but it is showing me this error. enter image description here AND GUYS I'M NEW TO DJANGO SO PLEASE EXPLAIN IN SIMPLE WORDS. -
I'm trying to push to Heroku but I get an Error
remote: -----> Python app detected remote: -----> Installing python-3.6.10 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: Sqlite3 successfully installed. remote: -----> Installing requirements with pip remote: Collecting Django<2.2.0,>=2.1.3 remote: Downloading Django-2.1.15-py3-none-any.whl (7.3 MB) remote: Collecting djangorestframework<3.10.0,>=3.9.0 remote: Downloading djangorestframework-3.9.4-py2.py3-none-any.whl (911 kB) remote: Collecting psycopg2<2.8.0,>=2.7.5 remote: Downloading psycopg2-2.7.7-cp36-cp36m-manylinux1_x86_64.whl (2.7 MB) remote: Collecting Pillow<5.4.0,>=5.3.0 remote: Downloading Pillow-5.3.0-cp36-cp36m-manylinux1_x86_64.whl (2.0 MB) remote: Collecting flake8<3.7.0,>=3.6.0 remote: Downloading flake8-3.6.0-py2.py3-none-any.whl (68 kB) remote: Collecting pytz remote: Downloading pytz-2019.3-py2.py3-none-any.whl (509 kB) remote: Collecting mccabe<0.7.0,>=0.6.0 remote: Downloading mccabe-0.6.1-py2.py3-none-any.whl (8.6 kB) remote: Collecting pyflakes<2.1.0,>=2.0.0 remote: Downloading pyflakes-2.0.0-py2.py3-none-any.whl (53 kB) remote: Collecting pycodestyle<2.5.0,>=2.4.0 remote: Downloading pycodestyle-2.4.0-py2.py3-none-any.whl (62 kB) remote: Installing collected packages: pytz, Django, djangorestframework, psycopg2, Pillow, mccabe, pyflakes, pycodestyle, flake8 remote: Successfully installed Django-2.1.15 Pillow-5.3.0 djangorestframework-3.9.4 flake8-3.6.0 mccabe-0.6.1 psycopg2-2.7.7 pycodestyle-2.4.0 pyflakes-2.0.0 pytz-2019.3 remote: remote: -----> $ python app/manage.py collectstatic --noinput remote: /app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. remote: """) remote: Traceback (most recent call last): remote: File "app/manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", … -
UNIQUE constraint failed: new__users_profile.user_id. Python Django
django.db.utils.IntegrityError UNIQUE constraint failed: new__users_profile.user_id Error occurs when I'm trying to register new user, login to an existing user and when I am trying to migrate. I've tried to delete all migrations and migrate once again but it didn't help models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' class Media(models.Model): image_name = models.CharField(max_length=50) image_description = models.CharField(max_length=80) image_image = models.ImageField(upload_to='media', default='default.jpg') views from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .forms import UserRegisterForm, MediaForm from .models import Media def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'GET': media_images = Media.objects.all() context = { 'media_images':media_images, } return render(request, 'users/profile.html', context) @login_required def add_media(request): if request.method == 'POST': form = MediaForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('http://127.0.0.1:8000/') else: form = MediaForm() return render(request, 'users/add_media.html', {'form':form}) -
how to deploy Angular and Django app on AWS EC2?
I have been following the deployment of the Django app on the EC2 instance from here However, I am developing my app with Django rest-framework now and my front-end will be on Angular. How would I deploy both apps? If anyone can direct me to any good reference would be much appreciated. -
Django/Bootstrap : how to force brower zoom?
I have a little problem with my website : with a default zoom level of 100%, everything is too big (the pictures, the texts, ...) while it looks really good with a zoom level of about 50%. Is there a way to force this zoom level by default when someone access the website ? If the answer is yes, is it possible to change that value of default zoom level depending on the screen size ? Because on my big computer, the perfect zoom level is 67% while on my computer sister it is 50% and on mobile it's even lower. Thanks in advance ! -
Django aggregation. How to render its value into the template?
I have came across on one of the weirdest problem which I literally can't understand. Well I was following This, but nothing helped. As the question says, I just want to render the result into the template. Below is my code. Views.py ... invoice = lead.invoice_set.all() total_invoice = invoice.aggregate(total=Sum('amount')) context = { 'total_invoice' : total_invoice } html {{total_invoice.total}} This is my code which according to the documentation has to work and as it suggested on the link I've shared. Unfortunately, Its not working for I don't know what reason. Below is what I've tried so far. TRY 1 When I try to print this into terminal it brings me a dictionary. for example. print(total_invoice) prints on terminal... {'total': 70000} Which is quite understandable. Now I would want to extract the value and that can be done by simple {{total_invoice.total}}. But it shows nothing on the template. TRY 2 (Working) Since I was trying different ways to render the value into the template, I came across this weird solution. I don't know how is this working. What I did different from TRY 1 here is just changing the variable name(total_invoice) to (total) and it worked perfectly fine. Here its how. Views.py … -
Django crispy form fields is not saving
Im trying formatting with Django crispy forms, but its not possible to save. first some code: forms.py class CreateForm_test(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Name'})) street = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Street'})) number = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Number'})) comment = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Comment'})) phone = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Phone'})) status = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Status'})) class CrispyAddressForm(CreateForm_test): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('name', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), 'street', 'number', Row( Column('comment', css_class='form-group col-md-6 mb-0'), Column('phone', css_class='form-group col-md-2 mb-0'), Column('status', css_class='form-group col-md-2 mb-0'), css_class='form-row' ), Submit('submit', 'Submit') ) views.py class CreateRegisterView(CreateView): model = Register message = _("saved") form_class = CrispyAddressForm template_name = 'register_form.html' def form_valid(self, form): if self.request.user.is_authenticated: form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): messages.success(self.request, self.message) return reverse('home') register_form.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} {% crispy form %} {% endblock %} When I open the form in my Browser, I got this error forms.py", line 36, in __init__ super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'instance' [29/Feb/2020 18:40:13] "GET /Register/create/ HTTP/1.1" 500 115893 I tried also with class CreateRegisterView(FormView): but then I get the same error to the views in this line form.instance.user = self.request.user -
how to display a field name in Django Rest Framework One To Many Relationship
I have a 2 models (products and CartList) and 2 serializer class(productSerializer and CartListSerializer and i wan my customers to be able to select a product and select the number of quantity for that product, so if but the issue i'm having is if it don't include the assign the Product serializer class to the product field when the user select the product, at the api endpoint only the product will display, not the product name, on the other hand if i assign the product serializer to the product and set read_only=True then user won't be able to select the product the want, and if i set write_only=True then they user will b able to modify other fields in the Product model, all i wan i for the user to be able to select the product_name and see the price for each item, please i need help fixing this, below is my model and serializer classes CARTLIST SERIALIZER class CartListSerializer(serializers.ModelSerializer): product = ProductListSerializer( many=True ) user = Userserializer(read_only=True) class Meta: model = CartList fields = ('user', 'product', 'quantity',) def create(self, validate_data): product_data = validate_data.pop('product') cart = CartList.objects.create(**validate_data) for product in product_data: Product.objects.create(cart=cart, **product) return cart PRODUCT SERIALIZER class ProductListSerializer(serializers.ModelSerializer): class … -
Django ForeignKey with through parameter
My problem originally was how to make fields show of a Foreignkey that is in ModelForm. I have solved this problem with this code but I can't get it to work. The following models make my code class DocAide(models.Model): id = models.AutoField(primary_key=True) pulse = models.DecimalField('Pulse', max_digits=3, decimal_places=0, blank=True, null=True) weight = models.DecimalField('Weight (kg)', max_digits=3, decimal_places=0, blank=True, null=True) bp_sys = models.DecimalField('BP Sys', max_digits=3, decimal_places=0, blank=True, null=True) bp_dia = models.DecimalField('BP Dia', max_digits=3, decimal_places=0, blank=True, null=True) temperature = models.DecimalField('Temp. deg C', max_digits=2, decimal_places=1, blank=True, null=True) scans = models.ManyToManyField(Scan, blank=True) tests = models.ManyToManyField(LabTest, blank=True) date = models.DateField(editable=False, default=timezone.now) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) created_by = models.ForeignKey(Doctor, on_delete=models.CASCADE, blank=True, null=True) no_charge = models.BooleanField('No Charge from Patient', default=False) doctors_notes = models.TextField('Patient is complaining about:', default='') part_to_scan = models.CharField(max_length=100, default='N/A', blank=True, null=True) part_to_xray = models.CharField(max_length=100, default='N/A', blank=True, null=True) note = models.TextField(max_length=100, default='') and class PrescriptionLine(models.Model): drug = models.ForeignKey(to=Drug, related_name='prescriptionlines', on_delete=models.CASCADE) doc_aide = models.ForeignKey(to=DocAide, related_name='prescriptionlines', on_delete=models.CASCADE) morning = models.CharField(validators=[int_list_validator], max_length=3, default=0) midday = models.CharField(validators=[int_list_validator], max_length=3, default=0) evening = models.CharField(validators=[int_list_validator], max_length=3, default=0) night = models.CharField(validators=[int_list_validator], max_length=3, default=0) days = models.CharField(validators=[int_list_validator], max_length=3, default=0) tablets = models.CharField(validators=[int_list_validator], max_length=3, default=0) My Forms looks like this: class DocAideForm(forms.ModelForm): class Media: css = {'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n/',) class Meta: model = DocAide fields … -
How can I send an email with the data posted on a class-based form in Django
I have a class-based view on my django app that grabs quote requests that are filled in the form and stores that information in the database. I'd like to use send myself and email when somebody does that and include the data in the mail subject and message. I got the e-mail part right and I can send a predefined message. but can't find a way to use the entered information. Here's what I have so far: urls.py urlpatterns = [ path('', views.index, name='index'), path('quote/', QuoteCreateView.as_view(), name='quote'), path('quote/thankyou/', views.quoteThankyou, name='quote_thankyou'), ] views.py class QuoteCreateView(CreateView): login_required = False model = Quote fields = ['fullname','email','date','description'] def form_valid(self,form): form.instance.author = self.request.user return super().form_valid(form) def quoteThankyou(request): subject = 'Message subject' message = 'Message' send_mail( subject, message, 'sender@email.com', ['receiver@email.com'], fail_silently=False, ) return render(request,'blog/quote_thankyou.html') models.py class Quote(models.Model): fullname = models.CharField(max_length=100) email = models.EmailField(max_length=100) date_sent = models.DateTimeField(default=timezone.now) date = models.DateTimeField() description = models.TextField() def __str__(self): return self.fullname def get_absolute_url(self): return reverse('quote_thankyou', kwargs={}) I appreciate your help. -
AttributeError: 'LoginForm' object has no attribute 'get' and response.get('X-Frame-Options') is not None
I get the following error no matter what way I do achieve my forms. This happens when I go to the URL of my form. When I go to the dashboard I need login first then it shows an error, this is my console's server Internal Server Error: /login/ Traceback (most recent call last): File "D:\Monthly Deposite System\mds\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\Monthly Deposite System\mds\env\lib\site-packages\django\utils\deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "D:\Monthly Deposite System\mds\env\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'LoginForm' object has no attribute 'get' [01/Mar/2020 00:17:54] "GET /login/?next=/dashboard/ HTTP/1.1" 500 65477 Internal Server Error: /login/ Traceback (most recent call last): File "D:\Monthly Deposite System\mds\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\Monthly Deposite System\mds\env\lib\site-packages\django\utils\deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "D:\Monthly Deposite System\mds\env\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'LoginForm' object has no attribute 'get' [01/Mar/2020 00:17:55] "GET /login/?next=/dashboard/ HTTP/1.1" 500 64940 forms.py class LoginForm(forms.Form): username = forms.CharField( widget=forms.TextInput( attrs={ "placeholder" : "Username", "class" : "form-control form-control-lg" } )) password = forms.CharField( widget=forms.PasswordInput( attrs={ "placeholder" : "Password", "class" : "form-control form-control-lg" } )) def clean(self, *args, **kwargs): username = … -
What is the Best practices of working with Dockerized Django and RDS?
I am working on developing a Django app that will use RDS Postgres as a production DB, I will containerize the web app in docker. What is the best way to set up a local development environment that works with the DB, and at the same time it has data like production? -
Django: How to Inject New BaseCommand Argument
In method BaseCommand.create_parser(), a default set of arguments are created and parsed for all subclassed commands. What is the best way to extend this method to add an additional argument? One option to effect the desired behavior is to override each of the available commands, extending the add_arguments() method (as shown below); I would much rather avoid this as it sounds like a maintenance nightmare. Desired Behavior The following module overrides the print_settings command provided by django-extensions to provide add the desired argument to a single command. However, I want to add this argument to all commands in my application. """Override the ``print_settings`` command provided by ``django-extensions``. Add support to load a specified config file. .. module:: odlogging.management.commands.print.settings :synopsis: override the ``print_settings`` command provided by ``django-extensions`` .. moduleauthor:: Bryant Finney <bryant@outdoorlinkinc.com> :github: https://github.com/bryant-finney/ """ # stdlib import logging from pathlib import Path from typing import Any # django packages from django.core.management import base # third party from django_extensions.management.commands import print_settings # local from odlogging.common import config_parse logger = logging.getLogger(__name__) class Command(print_settings.Command): """Override the ``print_settings`` command to config files.""" def add_arguments(self, parser: base.CommandParser): """Add the ``--config`` argument for specifying the environment configuration. :param parser: the parser used for parsing command arguments … -
Django Channel Error: No handler for message type websocket.receive
thread.html <script> //console.log(window.location) var loc = window.location var formData = $("#form") var msgInput = $("#message_id") var wsStart = 'ws://' if (loc.protocol == 'https:') { wsStart = 'wss://' } var endpoint = wsStart + loc.host + loc.pathname // EndPoint of the connection var socket = new WebSocket(endpoint) socket.onmessage = function(e){ console.log("message: ", e)} socket.onopen = function(e){ console.log("open: ", e) socket.send("Cool guys") //TRYING TO SEND THIS VIA THE SOCKET } socket.onerror = function(e){ console.log("error: ", e)} socket.onclose = function(e){ console.log("close: ", e)} </script> consumers.py import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread, ChatMessage class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print("Connected", event) await self.send({ "type": "websocket.accept" }) # other_user = self.scope['url_route']['kwargs']['username'] # me = self.scope['user'] # thread_obj = await self.get_thread(me, other_user) # print(other_user, me) # print(thread_obj) async def websocket_recieve(self, event): print('Recieve', event) await self.send({ "type": "websocket.send", "text": event, }) front_text = event.get('text', None) if front_text is not None: msg_json_dict = json.loads(front_text) msg = msg_json_dict.get('message') print(msg) await self.send({ "type": "websocket.send", "text": msg, }) async def websocket_disconnect(self, event): print("Disconnected", event) # @database_sync_to_async # def get_thread(self, user, other_user): # return Thread.objects.get_or_new(user, other_user)[0] error given File "/home/pentester/.local/lib/python3.7/site-packages/channels/consumer.py", line 75, in dispatch raise ValueError("No handler for … -
Trying to implement Bootstrap 4 in Django Project.Getting issue in Navbar Dropdown when adding link to custom css
<link rel="stylesheet" type="text/css" href="{% static 'ml/css/bootstrap.min.css' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'main.css' %}"/> <script src="{% static 'ml/js/jquery.min.js' %}"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="{% static 'ml/js/bootstrap.min.js' %}"></script> When I removed main.css link in my code dropdown is shown but including main.css in my code, dropdown is not displayed.I want to customize bootstrap code by adding custom style file for it but getting issue. <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Yartsa</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data- target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home </a> </li> <li class="nav-item dropdown" id="Arquivos"> <a class="nav-link dropdown-toggle" href="#" data-target="#Arquivos" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Projects </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink" id="MyArqs"> <a class="dropdown-item" href="#">Logistic Regression</a> <a class="dropdown-item" href="#">Misspellings</a> </div> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </nav> -
How to serve static files with Django in root
My question is fairly similar to the following except than for the new Django version (3.0.3): Django serve static index.html with view at '/' url Serving static files from root of Django development server I have an Angular project. Django only provides API/Admin views. How can I let Django serve the front end containing index.html, js, and CSS folder at the root? So example.com/index.html and example.com/CSS/style.css should become valid URLs as well as example.com/admin. It seems that setting STATIC_URL = "/" does not work. -
Handling Django Static Files in production
DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_files/')] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I've deployed my project on the digital ocean but after setting "DEBUG = False", static files (CSS, js, image) are not loading. I also tried giving STATICFILES_DIRS but still, nothing changed. -
How to add a Python Django video field
I am making an online school project and trying to make a python Django video field, so I can Upload a tutorial, any one knows how? please help. THANK YOU SO MUCH -
Using Django how can I import one react component into another?
I am trying to import one react component into another but have failed to do so. Here's my HTML which is in the Django templates directory:- {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>React Hello World</title> <script src="{% static 'js/react_cdn/react.production.min.js' %}"></script> <script src="{% static 'js/react_cdn/react-dom.production.min.js' %}"></script> <script src="{% static 'js/react_cdn/babel.min.js' %}"></script> <script type="text/babel" src="{% static 'js/components/App.jsx' %}"></script> </head> <body> <div id="root"></div> </body> </html> The App.jsx that I am loading here has the following code :- const { Component } = React; const { render } = ReactDOM; import Greet from './components/Greet.jsx' class App extends React.Component { render() { return ( <div> <Greet /> </div> ); } } ReactDOM.render(<App />, document.getElementById("root")); Now in this App.jsx I am trying to load my Greet.jsx which is again located at /static/js/components/Greet.jsx The error that I got was :- App.jsx:3 Uncaught ReferenceError: require is not defined To avoid this error I imported 'Greet.jsx' as:- const { Greet } = './components/Greet.jsx' But doing so gave me Error:- Invariant Violation: Minified React error #130; visit https://reactjs.org/docs/error-decoder.html?invariant=130&args[]=undefined&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings. The Greet.jsx looks … -
How to link fixed choices to new created questions in django
I'm very new as a django developer and I'm attempting to build a ranking web app. What I wanted to do is once a new question is created by the user through a crispy form, automatically changed the m2m model and link that new question with the choices. The choices are a fixed rank from 1 to 5 and they cannot be manipulated by users and not showing on the question create form. From what I read, I guess that this operation could be done by m2m_changed signal (or post_save, not sure), but I'm not really familiar with its functionality. I tried several times on differents ways but I'm not addresing good results. When I go to the admin page and set the choices to the new question manually this works perfect; same thing when I create the question and run the for loop by command line through the shell, but what I want is automate this process when the question is created by users. Sorry for the extensive, hope to be clearly enough! Thanks for the help!! I breakdown my codes below. models.py class Choice(models.Model): choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class Question(models.Model): choice = … -
Displaying the value of ManyToMany relationship in django admin
I am trying to display a brand of a bike in my django admin panel. I have managed to display the title, but I am struggling with the brand. Here's my models.py: class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) category = models.ManyToManyField(Category, blank=True) image = models.ImageField(upload_to='bikes') brand = models.ManyToManyField(Brand, null=True) def __str__(self): return self.item.title class Brand(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name I have tried that: def __str__(self): return self.brand.name But nothing is displaying then. Any ideas how to display the self.item.title and brand name at the same time?