Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with Djago {% extends %} templating
I am building a webapp with Django and Python 3.7 and I'm really confused by this simple thing: These are my templates. They are all in the same directory. When I try to call {% extends 'store.html' %} , I get TemplateDoesNotExist at /publicaciones/ and it points to store.html. This is in publicaciones.html. Here's the template: publicaciones.html: {% extends "store.html" %} {% load static %} {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/style_reset-pass.css' %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title>Publicaciones</title> </head> <body> <div class="container"> {% block content %} {% for item in items %} {{ item|crispy }} {% endfor %} {% endblock content %} </div> </body> </html> What am I missing? Please ask if you need any other code. I'll answer immediately. -
Django rest framework, use none in model's field
I have a Django rest framework API, In one of the models, there is a field for GeoLocation's elevation, which defaults its value to None. The reason for that is that it can be passed in by the user or if left empty, obtained by a call to google's elevation API. So, I'm trying to use the create function in the serializer to define its value but I'm getting a key error: #app/models.py elevation = models.FloatField(name="Elevation", max_length=255, help_text="If known, Add location's sea level height. If not, Leave Empty.", null=False, default=None) #app/serializers.py from rest_framework.serializers import HyperlinkedModelSerializer from Project_Level.utils import get_elevation from .models import KnownLocation class KnownLocationSerializer(HyperlinkedModelSerializer): def create(self, validated_data): if validated_data["Elevation"] is None: # Using if not validated_data["Elevation"] results the same. validated_data["Elevation"] = get_elevation(validated_data["Latitude"], validated_data["Longitude"]) class Meta: model = KnownLocation fields = ('id', 'Name', 'Area', 'Latitude', 'Longitude', 'Elevation') Error: KeyError at /knownlocations/ 'Elevation' Exception Location: KnownLocation/serializers.py in create, line 9 -
Save into MongoDB from views in django
Hello i am facing a problem when im trying to store in my MongoDatabase some data via views.py My question may be silly cause im new to django... So i have a ModelForm in my forms.py class LanModelForm(forms.ModelForm): project_name = forms.CharField() target = forms.GenericIPAddressField() class Meta: model = UsersInput fields = ('project_name', 'target',) and my model in models.py class UsersInput(models.Model): project_name = models.CharField(max_length=15) ip_subnet = models.GenericIPAddressField() I submit the form and when i go to the admin page to inspect my (UsersInput) object only project name is passed. Target field is empty. Code in views.py def post(self, request): form = self.form_class(request.POST) if form.is_valid(): _target = form.cleaned_data['target'] project_name = form.cleaned_data['project_name'] form.save() return redirect('/passive_scanning.html') -
How to display a video in django
I want to do an HTML file in my django project that includes a video from the server computer. The video is in the server computer and the client that enter to the site should see the video. How should I do this? -
Can not add values from forms to Django models
I made a form and there I had a multiple-choice field called artists which I got from my database and while adding a song a user can select multiple artists and save the song. The artists are a ManyToManyField in Django models. models.py class Artists(models.Model): """ Fields for storing Artists Data """ artist_name = models.CharField(max_length = 50, blank = False) dob = models.DateField() bio = models.TextField(max_length = 150) def __str__(self): return self.artist_name class Songs(models.Model): """ Fields for storing song data """ song_name = models.CharField(max_length = 30, blank = False) genre = models.CharField(max_length = 30, blank = False) artist = models.ManyToManyField(Artists) release_date = models.DateField() forms.py class Song_input(forms.Form): queryset = Artists.objects.only('artist_name') OPTIONS = [] for i in queryset: s = [] s = [i, i] OPTIONS.append(s) artist_name = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=OPTIONS) song_name = forms.CharField() genre = forms.CharField() release_date = forms.DateField(widget=DateInput) Now I want to get all the values selected from the form and save to my database. Here the artist_name may have multiple values. I have tried using the add() and create() methods but can not figure out how to add all the data where one field (artist_name) having multiple data to my database. -
DRF permission issue even after sending a valid token for a get request
serializer.py class UserDetailSerializer(serializers.ModelSerializer): """for all getting all objects of a particular user """ tags = TagListSerializerField() author=serializers.StringRelatedField(read_only=True) class Meta: model = Post fields = ('id','title','rate','author','content','review','url','tags') views.py class PostListUser(generics.ListAPIView, APIView): serializer_class = UserDetailSerializer permission_classes = [IsAuthenticated] authentication_classes =(TokenAuthentication,JSONWebTokenAuthentication) def get_queryset(self): return Post.objects.filter(author=self.request.user) urls.py url('^me/$', PostListUser.as_view()), but when i tried to hit a get request with all the Authorization headers I have got this response { "detail": "You do not have permission to perform this action." } -
Django form isn't showing the correct fields
The django form to let users change their information fields should let them change username, email, name and last_name, but instead, it shows their nationality, gender, score on app and birthday. views.py def profileedit_view(request): if request.method== 'POST': form= PerfilEditadoForm(request.POST, instance = request.user) if form.is_valid(): form.save() return redirect('login') else: form= PerfilEditadoForm(instance=request.user) args= {'form': form} return render(request, 'profileedit', args) form = UsuarioForm(request.POST or None) if form.is_valid(): form.save() context = { 'form': form } return render(request, "profileedit.html", context) forms.py class PerfilEditadoForm(UserChangeForm): class Meta: model = User fields= ('email', 'username', 'first_name', 'last_name') profileedit.py <form method="POST" action="#"> {% csrf_token %} <p> {{ form.as_ul }} <button class="btn btn-primary py-1 px-2" type="submit" > Save </button> </p> </form> -
mysqlclient install error in python 3.7.4 windows
I created Django project and want to connect with mysql. So, I should install mysqlclient on my win10 system. my command : pip install mysqlclient then I got this error ERROR: Command errored out with exit status 1: command: 'c:\users\2020\appdata\local\programs\python\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\2020\\AppData\\Local\\Temp\\pip-install-o06onpbq\\MySQL-python\\setup.py'"'"'; __file__='"'"'C:\\Users\\2020\\AppData\\Local\\Temp\\pip-install-o06onpbq\\MySQL-python\\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\2020\AppData\Local\Temp\pip-record-sdzwwsuw\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\2020\appdata\local\programs\python\python37-32\Include\MySQL-python' cwd: C:\Users\2020\AppData\Local\Temp\pip-install-o06onpbq\MySQL-python\ Complete output (29 lines): running install running build running build_py creating build creating build\lib.win32-3.7 copying _mysql_exceptions.py -> build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building '_mysql' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -Ic:\users\2020\appdata\local\programs\python\python37-32\include -Ic:\users\2020\appdata\local\programs\python\python37-32\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt" /Tc_mysql.c /Fobuild\temp.win32-3.7\Release\_mysql.obj /Zl _mysql.c _mysql.c(42): fatal … -
Why do django render a view with "\n" ? (js parse error)
I'm trying to render a view in Django and send it with ajax to a client. My view.py : def searchUser(request): form = Search(request.POST['name']) found_profiles = User.objects.prefetch_related('profile').filter(artist_name__icontains=request.POST['name'])[:20] profiles = {} i = 0 for user in found_profiles: profile = Profile(user = user) profiles.update({i : {'user' : user,'profile' : profile}}) i+=1 print('profile '+str(profiles)) return render(request, 'home_page/search_results.html', {'profiles' : profiles}) My search_result.html : {% for tuple, cont in profiles.items %} <h2>{{cont.user.email}}</h2> <h2>{{cont.user.artist_name}}</h2> <h2>{{cont.profile.bio}}</h2> {% endfor %} And finally my js : <script type="text/javascript"> $('#submit-search-user').on('click', function(){ var name = $('#id_Name').val(); console.log("Seaching for "+name); $.ajax({ type: "POST", url: "/ajax/search/user", data: {name: name, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType : 'json', error : function(xhr, errmsg){ console.log(xhr); console.log(errmsg); }, success : function(data) { console.log(data) $('#result').html(data); } }); }); </script> Js output a parse error, the "responseText" part is : "\n\n\t<h2>test@outlook.fr</h2>\n\t<h2>Azerrt</h2>\n\t<h2></h2>\n\n\t<h2>moowee@yo.de</h2>\n\t<h2>a</h2>\n\t<h2></h2>\n\n" Why is there any "\n" and "\t" ? Is this the reason of my parse error ? -
i want equivalent django query for follwing Sql query,
SELECT roomid FROM hotel WHERE book_date >= startdate AND book_date < enddate GROUP BY roomid HAVING sum(booked=1)=0 or if there is any way to convert raw queries output to Django queryset for eg. 1. objectQuerySet = Article.objects.filter(booked=1) print(type(objectQuerySet)) >> <class 'django.db.models.query.QuerySet'> 2. with connection.cursor() as cursor: query = "select * FROM api_basic_article WHERE booked = 1" cursor.execute(query) queryset = cursor.fetchall() print(type(queryset)) >><class 'list'> can I convert list object to django.db.models.query.QuerySet? my final aim is to response a json serialized file for the rest api request at django -
What is the best way to create django app for language learning
I currently want to create an app built on Django. I had some experience with this framework a year ago but I gave up eventually. And now I want to go back to development. And so I decided to create an app for learning 500 most used words in the English language. I've basically made everything look nice and smooth, but I got stuck in the back-end part. And I seek advice, how to create an interactive app for the flashcard web app. What libraries are used in the most advanced Django apps(I'm okay with reading a lot of material), how to authorize with google accounts, how to collect data from users and know the statistics of the app. I've read the documentation, watched a lot of tutorials, but they basically teach the low skill stuff and nothing else. My question is if you were to create an advanced Django app for memorizing 500 frequently used words in the English language, what would you use?. How would you do it?. In what order? -
Which one of LF and CRLF should I use in a django project?
I am collaborating on a course-django project with other several students, and I found line separator mixed up, some files use LF, and other files use CRLF. I feel confused, although now everything is well, no one knows future. so which one we should set in project level? do you have any suggestions? -
html page is loaded from disk cache but event.persisted is false
I have this to my javascript file: window.addEventListener('pageshow', function(event) { if (event.persisted) { console.log('Page was loaded from cache.'); } }); but if i navigate to another link and then hit back button, my html page is loaded from disk cache and the event.persisted is false. Any suggestions? -
How to increase timeout while uploading on the Sanic framework?
I have a method in Sanic for uploading files. Sometimes my file size is large or the connection between server and clients is poor So, in this situation I lose my request because the clients occur with a timeout exception. I want to increase timeout on top of a specific method. # I want to define set timeout period here # @set_imeout(4 * 60) @song.route('/upload', methods=["POST"]) @is_authenticated() @required_roles(['cafe']) @jsonify async def process_upload(request): # upload method do something for upload -
How to protect page by password
I have a project where users can join rooms, but i want to protect room with password.How to implement that? Maybe some decorators or something like that -
create django model with field names from list
I have a django model in my models.py file like this: class Inventory(models.Model): player = models.CharField(max_length=30) apples = models.IntegerField() bananas = models.IntegerField() Where each "player" has different numbers of fruits in his inventory. I will change the possible fruits over time, thus I would like to create these fields dynamically from a list. So right now the list would be ["apples", "bananas"] but at a later point in time I would like to have ["apples", "oranges", "lemons"]. Is there a way to create the field names from a list? -
TravicCI build dont find Managa.py [Django] command
im following a tutorial and a complete newbie. in the tutorial the tutor used docker as virtual envioremnt and because im currently using my Win-10-Home machine i've decided to use plain 'ol python venv. for some reason TravicCI is not fiding my manage.py command, and i cant figure out why! this is the TCI log 0.58s$ git clone --depth=50 --branch=master https://github.com/therealgenish/recipe-app-api.git therealgenish/recipe-app-api $ source ~/virtualenv/python3.6/bin/activate $ python --version Python 3.6.7 $ pip --version pip 19.0.3 from /home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pip (python 3.6) install $ pip install -r requirments.txt $ app\manage.py test && flake8 appmanage.py: command not found The command "app\manage.py test && flake8" exited with 127. Done. Your build exited with 1. the reason it's app\manage.py and not manage.py is because it's outside the app folder, so i figured.. the .travis.yaml : language: python python: - 3.6 install: - pip install -r requirments.txt script: - app\manage.py test && flake8 and a link to the github project -
How to differentiate between modules with same name in Django
For example, there is a 'reverse' module in Django which you can use for easy navigation between links. There is also a 'reverse' module available in DRF which can be used for creating custom API endpoints easily. I'm sure people at some point need to use both the modules at different stages, but how is Django going to differentiate between these two modules? They are called almost in the same way. Or am I wrong? Maybe either of the modules can be use to carry out both the tasks? -
Dependent Nested Category in Django
I want to create 2 category 1 Main category ex a. MEN b. Woman and 2 Subcategory would be according to parent category. How I can perform these actions. class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey( Category, null=True, blank=True, related_name='children', on_delete=models.CASCADE ) def __str__(self): return self.name def save(self, *args, **kwargs): # prevent a category to be itself parent if self.id and self.parent and self.id == self.parent.id: self.parent = None super().save(*args, **kwargs) class Product(models.Model): categories = models.ForeignKey( Category, related_name='products', blank=True, on_delete=models.CASCADE ) categorychild = models.ForeignKey(SubCategory, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=255) How I can solve this Im putting this question 3rd time Please help -
Separate media settings for each app in django
I am working on building a django based blog-like site, it currently has one app. It contains a media folder which contains the images uploaded by the user. However, the MEDIA_URL and MEDIA_ROOT are specified in the main settings.py file. But in the future, there will be more apps containing more media, thus I want separate MEDIA_URL(s) and settings for each app. I tried writing the MEDIA_ROOT and MEDIA_URL separately in the apps.py file, but removing this from the main settings.py file results in an error. I also tried using FileSystemStorage, but even this needed me to have a MEDIA_URLS in the settings.py file. Please let me know if you need any more details. Any help is appreciated, thanks. -
Django Email - [Errno 2] No such file or directory
I am looking to allow the user to upload and send a document via email from my django app. When I go to send the email I get the error "[Errno 2] No such file or directory:". I have tried using a relative path as well as specifying the path but I get the same error either way. I can see that the file is being successfully loaded to that location...so I feel I must be missing something obvious here. Here is my view: def email(request): if request.method == "POST": form = EmailForm(request.POST,request.FILES) if form.is_valid(): post = form.save(commit=False) # post.published_date = timezone.now() post.save() email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') document = request.FILES.get('document') email_from = settings.EMAIL_HOST_USER recipient_list = [email] email = EmailMessage(subject,message,email_from,recipient_list) base_dir = 'media' email.attach_file('Desktop/WBU2/Poseidon/media/media/'+str(document)) #also tried email.attach_file('/media/'+str(document)) email.send() else: form = EmailForm() return render(request, 'docemail.html', {'form': form}) models.py class Mails(models.Model): email = models.EmailField() subject = models.CharField(max_length=1000) message = models.CharField(max_length=20000) document = models.FileField(upload_to='media') def __str__(self): return self.email -
cleaned_data for extra fields in django ModelForms
I have the ModelForm below with an extra field named decimal_part: class MyObjectForm(forms.ModelForm): class Meta: model = MyObject exclude = [] def __init__(self, *args, **kwargs): super(MyObjectForm, self).__init__(*args, **kwargs) self.fields['decimal_part'] = forms.IntegerField( required=False, label=mark_safe('<br/>'), widget=forms.NumberInput( attrs={ 'type': 'text', 'data-type': 'number', 'placeholder': ' cm', 'maxlength': '2', })) def clean_decimal_length(self): data = self.cleaned_data['decimal_part'] return data and the template: <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <table> #...some form attr.s ...# {{ form.decimal_part}} </table> <input type="submit" value="Submit"> but after submitting the form correctly I'm getting a KeyError: 'decimal_part' data.get('decimal_part') returns None and decimal_part is not in self.cleaned_data any thoughts? thank you for you help! -
how to do Inner join using django orm
MY models.py class Forms_in_Document(models.Model): document_submit = models.ForeignKey(Document_submit, on_delete=models.CASCADE) class Document_data(models.Model): forms_in_document = models.ForeignKey(Forms_in_Document, on_delete=models.CASCADE) document_structure = models.ForeignKey(DocumentStructure , on_delete=models.CASCADE) date_created= models.DateTimeField(default=datetime.now(),null=False) string = models.CharField(null=True, max_length=100) integer = models.IntegerField(null=True) date_time = models.DateTimeField(null=True) class Application(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, null=False) date_created = models.DateTimeField(default=datetime.now(),null=False) forms_in_document = models.ForeignKey(Forms_in_Document, on_delete=models.CASCADE, null=True) closed = models.BooleanField(default=False, null=False) new = models.BooleanField(null=False) media = models.BooleanField(default=True) Path_info = models.ForeignKey(Path_info, on_delete=models.SET_NULL,null=True) The raw sql query that i am trying to do in django is "Select * from Application app inner join Document_data dd on dd.forms_in_document=app.forms_in_document where [some filter]" How can i do this using django Thanks in Advance -
Shared authentication between Laravel and Django apps coexisting in the same domain
I have a Laravel app which contains authentication code(and a lot more including Sass subscriptions and payment gateway integration), and a Django app which contains the main routes of the application. Both of them coexist in the same domain, let's say the Laravel app resides in the /auth url and the django project resides in the / url. I want to share the authentication between the two applications, (ie) if the user logs in using a Laravel form and is redirected to the Django route, he must stay authenticated. Any suggestions and links to relevant sources will be appreciated. Forgive me if the question seems too basic. Either of the applications can't be rewritten in another , since the Laravel app has too many functionalities to be rewritten and the Django part contains some machine learning functionality -
Probrems with URLconfs in Django
I include authentication URLconf in my urls.py: path('accounts/', include('django.contrib.auth.urls')), And it urlpatterns contains this: path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), path('password_change/', views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password_reset/', views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), But when I go to 127.0.0.1:8000/accounts debuger shows me this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts Using the URLconf defined in locallibrary.urls, Django tried these URL patterns, in this order: 1. admin/ 2. catalog/ 3. ^static\/(?P<path>.*)$ The current path, accounts, didn't match any of these. Why doesn't django see my URLconf?