Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to post pictures on django?
I have been trying to make my code able to post images but when I try to create the post, the part that is supposed to let me uploud a picture, the form of the picture doesn't appear. I was wondering if there is any way to make the code work, ther might be something wrong int he create view or the create.html, maybe urls. views.py def create(request): if request.method == 'POST': created_date = timezone.now() header1 = request.POST['header'] content1 = request.POST['content'] user = request.user form = PostForm(instance=user) context2 = {"form": form} created_obj = Create.objects.create(added_date=created_date, title=header1, content=content1, user=user) created_obj.save() print('create created') return redirect('home', context2) else: print('create not created') return render(request, 'create.html') models.py class Create(models.Model): added_date = models.DateTimeField() title = models.CharField(max_length=200) content = models.CharField(max_length=200) image = models.ImageField(null=True, blank=True, upload_to='images/') user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE, default=1) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' urls.py urlpatterns = [ path('', views.home, name='home'), path('create', views.create, name='create'), ] forms.py class PostForm(ModelForm): class Meta: model = Create fields = ['image'] exclude = ['user'] create.html {% extends 'home.html' %} {% block body %} <div style="margin-top: 200px; margin-left:200px;"> <form action="create" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="header" placeholder="Add here..."> <input type="text" … -
Django 3 ModelChoiceField stays empty
I have this form with two fields. The second field should be populated with the names of existing projects but when rendered is stays empty and no dropdown appears. class UploadRawForm(forms.ModelForm): orig_file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) project = forms.ModelChoiceField(queryset=Project.objects.all(), required=True) class Meta: model = RawFile fields = ['orig_file', 'project'] Template: {% extends 'base.html' %} {% block title %}File upload{% endblock %} {% block content %} <h1> {{ name }} </h1> <form method="POST" id="upload-form" class="upload-form" enctype="multipart/form-data" novalidate> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Upload</button> </form> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <p> {{ error }} </p> {% endfor %} {% endfor %} {% endif %} {% endblock %} -
How can I update a Django user's password from inside Postgres?
I'd like to reset a user password, but only have access to the Postgres database. Dropping in plaintext doesn't work, and the hashing process for Django appears to be too complex to replicate. Any thoughts? -
Django - Best way to organize/serve mostly static website?
My friend with very little coding experience began making a business site and passed it on to me. Currently, it is mostly static html and css files but I want to take what he has and build on it using Django because I will be adding features like user login/auth and checkout. I was wondering what the best thing to do with all these html and css files are and how I might go about fitting it to Django framework. All of the content on these pages will be static but I could imagine in the future once I add a login, the header might be different to show whether or not a user is logged in. Would I need to make separate apps for each page, include them all in one app, or just put them all in the static folder? -
Django Rest Framework - Uploading files link 404
I'm trying to upload a file (any file) to my rest framework. At the current time, I'm able to upload the file but unable to click on the generated link for some reason. This is my settings.py: ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATICFILES_DIRS = [os.path.join(BASE_DIR, "site_static")] STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' This is my model.py: ... class FileUpload(models.Model): created = models.DateTimeField(auto_now_add=True) user_profile = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) datafile = models.FileField(blank=False, null=False) This is my views.py: ... class FileUploadViewSet(viewsets.ModelViewSet): """Handles uploading a file""" authentication_classes = (TokenAuthentication,) serializer_class = (serializers.FileUploadSerializer) queryset = models.FileUpload.objects.all() parser_classes = (MultiPartParser, FormParser,) permission_classes = ( permissions.UpdateOwnStatus, IsAuthenticated ) def perform_create(self, serializer): """Sets the user profile""" serializer.save(user_profile=self.request.user, datafile=self.request.data.get('datafile')) This is my serializer.py: ... class FileUploadSerializer(serializers.HyperlinkedModelSerializer): user_profile = serializers.SlugRelatedField( read_only=True, slug_field='id' ) class Meta: model = models.FileUpload fields = ('id', 'user_profile', 'created', 'datafile') extra_kwargs = {'user_profile': {'read_only': True}, 'created': {'read_only': True}} This is my complete urls.py: router = DefaultRouter() router.register('hello-viewset', views.HelloViewSet, basename='hello-viewset') router.register('profile', views.UserProfileViewSet) router.register('feed', views.UserProfileFeedViewSet) router.register('upload', views.FileUploadViewSet) urlpatterns = [ path('hello-view/', views.HelloApiView.as_view()), path('login/', views.UserLoginApiView.as_view()), path('', include(router.urls)), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I upload a file, the datafile field becomes populated with the file location, such as: { "id": … -
Attribute Error: Django Model has no attribute 'instructor_name'
Trying to figure out why I'm getting an attribute error here. I've done this same process before in the Django tutorial, but here, I'm getting an attribute error using the same logic. from django.db import models from django.utils import timezone # Create your models here. class Department(models.Model): department_name = models.CharField(max_length=100) def __str__(self): return self.department_name class Instructor(models.Model): belongs_to = models.ForeignKey(Department, on_delete=models.CASCADE) instructor_name = models.CharField(max_length=100) def __str__(self): return self.instructor_name Like the documentation tutorial for Django, I am attempting to have an empty query set outputted while I'm in my python shell. When I create and save the data into the database, I come back and assign the data to an object by using d = Department.objects.get(pk=1) I get the desired output as I can call upon d.department_name and it'll output the name I originally assigned it. When I call upon d.instructor_name.all() the same way the tutorial does for q.choice_text.all() I am not returned with an empty query set, but rather this error: <ipython-input-18-29fd5cce7e1e> in <module>() ----> 1 d.instructor_name.all() AttributeError: 'Department' object has no attribute 'instructor_name' Not really sure what I'm doing differently here. I've read other posts with similar issues, but they're always doing something slightly different and I can't seem to … -
No module named 'portfoliodjango' error on manage.py
Got this error in djangoi while trying to use manage.py to runserver or migrate or anything using that file. My project name is website and app name is portfolio. Please Help :) Error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\nihaa\.virtualenvs\website-o1OcjGMR\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\nihaa\.virtualenvs\website-o1OcjGMR\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\nihaa\.virtualenvs\website-o1OcjGMR\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\nihaa\.virtualenvs\website-o1OcjGMR\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\nihaa\.virtualenvs\website-o1OcjGMR\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "c:\users\nihaa\appdata\local\programs\python\python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'portfoliodjango' -
How to restrict access to api except from the server?
I made a url that sends data from the database in json in order to see it with ajax, it sends data like this: { "image": "images/2020/example.jpg", "title": "example title" } but anyone who goes to the page source in html can see the url and can get the data and if they are hackers they can load the url multiple times until the website crashes. so how can I restrict accessing the data url only from the server? or is there a better way to do this. p.s I'm using django. THANKS -
Private messages between users in django
I understand there should be two tables: class Dialog (models.Model): user_1=models.ForeignKey(User, on_delete=models.CASCADE) user_2=models.CharField(max_length=100) def __init__ (self): return self.id class Message(models.Model): content=models.TextField(blank=True) user=models.ForeignKey(User, on_delete=models.CASCADE) dialgog=models.ForeignKey(Dialog) I can't link them in views.py file. Please, help -
Django procedural GET form, value issue
I'm building a procedural GET form in Django based on a serialized view (return JsonResponse(datas)). For some reasons, mainly because it's not based upon a model, I can't use a forms.ModelForm a dummy items look like that : {% for base in base_products %} <div class="field"> <div class="ui text field"> <input type="text" name="{{ base.name }}"> <label>{{ base.name | title}}</label> </div> </div> {% endfor %} I want my field to be in the show the value send by the request. For what I know of Django I should use the request and do something like that to access the value : value="{{ request.GET.my_field }}" So, here's my problem, my_field is now coming from {{ base.name }} and I can't do : value="{{ request.GET.{{ base.name }} }}" Do you guys have any idea how I can go with that ? thanks -
Django how to transform queryset into json?
My views.py looks like this: def index(request): mydata = mymodel.objects\ .values('district')\ .annotate(total=Count('district'))\ .order_by('total') aggregate = json.dumps(list(mydata), cls=DjangoJSONEncoder) context = {'aggregate': aggregate} return render(request, 'polls/index.html',context) and in my index.html, my code is this: var aggregate = '{{ aggregate }}' However, when I did console.log(aggregate) in the browser, it gives me this string: [{&quot;district&quot;: &quot;ISLINGTON&quot;, &quot;total&quot;: 663}, {&quot;district&quot;: &quot;HACKNEY&quot;, &quot;total&quot;: 669}, {&quot;district&quot;: &quot;HARINGEY&quot;, &quot;total&quot;: 1230}, {&quot;district&quot;: &quot;WALTHAM FOREST&quot;, &quot;total&quot;: 1947}] I expect this should be in the JSON format. I am still learning Django, could anyone help me on this? Thanks in advance! -
virtual env problems while cloning projects from github in different os
i've been looking for answers in stackoverflow and over all the web but still don't get it, i started a new project and upload it to a repository in github, all this i did it from a MAC computer, everything fine until here, but... i tried cloning my project in an Windows computer and i can not activate my venv, to activate the venv in MAC there is a bin file, so i type the following commands in the terminal, 'source bin/activate' and it works fine, but i understand that in windows there is a Script folder which i dont have because i created and activated my project for the first time in MAC, there is a way which is deleting the venv directory everytime i clone my project in a different OS but i dont think that's a good pratice, so i would like to know which is the correct way of doing this, which are your recommendations? Thanks. -
Specific message error for template django
I'm currently working on message error for template that show if you user already liked but it show all the error to all my book Here's my template: <form action="/books/{{book.id}}/like/" method="post" class="like"> {% csrf_token %} <button type="submit" class="btn far fa-thumbs-up"></button> {% if messages %} <ul class="messages"> {% for message in messages %} {% if "like_error" in message.tags %} <li class="text-danger">{{ message }}</li> {% endif %} {% endfor %} </ul> {%endif%} </form> Here's my def: def like(request, id): book = Book.objects.get(id=id) user = User.objects.get(id=request.session["user_id"]) like = Like.objects.get_or_create(u_like=user, b_like=book) if not like[1]: messages.error(request, "Already added to favorite", extra_tags="like_error") return redirect("/books/") context = { 'book_user_like': User.objects.get(id=request.session["user_id"]).user_like.all(), 'book': Book.objects.get(id=id), } return redirect(f"/books/{book.id}", context) and here's my models: class Like(models.Model): u_like = models.ForeignKey( User, related_name="user_like", on_delete=models.CASCADE) b_like = models.ForeignKey( Book, related_name="book_like", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
Multi-tenancy subdomains do not return anything
I had a single application running on AWS (NGINX + uWSGI) working normally, but I decided to use the Semi Isolated Approach strategy to create tenants. On my local server, I was able to create and access tenants (tenant01.localhost, tenant02.localhost), but I can't when I try to run on the AWS machine. In it, I don't have any type of error and my NGINX .conf file looks like this: upstream django { server unix:///home/ubuntu/folder_my_project/mysite.sock; # for a file socket } # configuration of the server server { listen 80; listen [::]:80; server_name ssh.18.xxx.xxx.xxx *.18.xxx.xxx.xxx; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/ubuntu/folder_my_project/media; } location /static { alias /home/ubuntu/folder_my_project/static; } location / { uwsgi_pass django; include /home/ubuntu/folder_my_project/uwsgi_params; } } # MY TENANCY server { listen 80; listen [::]:80; server_name ten01.18.xxx.xxx.xxx; charset utf-8; client_max_body_size 75M; location /media { alias /home/ubuntu/folder_my_project/media; } location /static { alias /home/ubuntu/folder_my_project/static; } location / { uwsgi_pass django; include /home/ubuntu/folder_my_project/uwsgi_params; } } Obs.: the journalctl doenst show me error. If anyone can show me what is missing from this file, I would be really grateful. -
Django printing into the browser console (something like console.log)
How to print a message in the visitor's browser console using Django? I know this makes a little sense from the production side, but I would like site visitors to be able to see what is going on "under the hood". I made a Django book recommending site to present my silks with Python and recommendation systems and in order to explain to the visitor how everything functions I need Django-Python equivalent of console.log in javascript. All the posts regarding Django logging are focused on logging information on the server side, but that is not what I am looking for. -
How to save django wizard form in step 1
My problem is I need to save the first form in the database so that I can use the data in the second form, is it possible to do that using django wizard ? any solution to this ?? views.py : lass ContactWizard(SessionWizardView): template_name = 'step1.html' def get_form(self, step=None, data=None, files=None): form = super(ContactWizard, self).get_form(step, data, files) # print self['forms']['0'].cleaned_data step = step or self.steps.current if step == '1': form.fields['Id_Achats'].initial = Achats.objects.latest('id') return form def done(self, form_list, **kwargs): for form in form_list: print(form.cleaned_data) form.save() return redirect('nadjib') forms.py : class AchatForm(ModelForm): class Meta: model = Achats fields = ('Date','Id_Fournis','Montant_HT','Montant_TVA','Montant_TTC') class AssociationForm(forms.ModelForm): class Meta: model = Association fields = ('Id_Achats', 'Id_Article', 'Prix_Unitaire', 'Quantite') -
How to make form on django base.html file
I am making a web application using Django. One of the features that i am trying to implement is a form that is located in the navbar. The form enables the user to enter how they are feeling,and is currently located in its own mood.html file. Is there a way to remove the form from its own file and add it to the base.html file so that it is accessible on all pages enabling the user to enter how they are feeling from any page? -
Running django script directly on server from command line throws error (Lost connection mysql)
I have a script I run from the command line on a server that works fine on my local computer but not on the server. if __name__=='__main__': # only those series titles that have 12 arima predictions selections_list=arima_predictions.objects.values('series_title').annotate(cnt=Count('id')).filter(cnt=12).values_list('series_title', flat=True).distinct() If I try to write the results of selections_list to a file I get an error that says django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query') If I don't try to write the results of selections_list to a file, I don't get an error, but it seems to just hang -
pycharm http client send request to Django runserver "Connection reset by peer"
Pycharm 2020.1 & Python 3.7.2 both Django 2.2.12 & 3.0.5 has below issue in dev server when sending a request with Pycharm HTTP integrated client (*.http) ### GET {{url}}/order/ Accept: application/json Cookie: sessionid={{sessionid}} I got this error now and then. System check identified no issues (0 silenced). April 29, 2020 - 08:41:27 Django version 3.0.5, using settings 'proj.settings.dev' Starting development server at http://127.0.0.1:8001/ Quit the server with CONTROL-C. [29/Apr/2020 08:41:53] "GET /api/order/ HTTP/1.1" 200 5070 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 49554) Traceback (most recent call last): File "/Users/CK/.pyenv/versions/3.7.2/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Users/CK/.pyenv/versions/3.7.2/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Users/CK/.pyenv/versions/3.7.2/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/Users/CK/Git/QIF/inventory/proj/.venv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/CK/Git/QIF/inventory/proj/.venv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Users/CK/.pyenv/versions/3.7.2/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer ---------------------------------------- upgrade python to 3.8.2 doesn't work. -
Django - cascade on other condition
I'm using Django and a Postgres database and I have two tables (Authors, Books). I don't want to enable to deletion of any records, instead to change the boolean of an unseen field called 'active' - a field both tables have. What i'd like to happen is when a user changes an Author's 'active' field to False, all of the books with a FK to this author in the Books table have their 'active' field's also set to False. In Django, my only options it seems related to deletion, how would I set this up with the models.py file? -
AWS S3 Bucket returning 403 forbiden
I have an application in Django and I put it my static files in a bucket on AWS S3. However, when I try to connect in my application the bucket S3 return 403 forbidden for static files. My bucket has a public access configurated for it. If I try to access the file directly an XML error is returned like: This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>2A64DBA5BD88AC1C</RequestId> <HostId> K7NHlv7xhPAL6626LCHLayoR4BauqARf6KaTtKUYKQsakNqQ1LL6RnuIwxUqjMP0q6UjMmiW7Yw= </HostId> </Error> My bucket has the files: I tried to change settings putting AWS_DEFAULT_ACL like 'public', 'private' and None, but the problem persists... Obs.: My app is in Heroku. How can I solve this problem? -
Why I am getting a filter error for my template tag?
I'm not sure why I am getting this filter error. I looked up other peoples similar issues with this, and I am definitely loading my template tag, I restarted the server, I have a template tags folder with an init.py file and the file that holds my tag, so , what am I doing wrong here? error is at {{ request.user|unread_messages }}, Invalid filter: 'unread_messages' unread_message_counter.py from django import template from dating_app import models register = template.Library() @register.simple_tag def unread_messages(user): return user.InstantMessage.filter(viewed=False).count() **base.htmnl ** {% load bootstrap4 %} {% load unread_messages_counter %} <!-- Navbar is located in this file --> <!doctype html> <html lang="en"> <head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> {% block head %} <title>Basee</title> {% endblock %} </head> <body> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExampleDefault"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'dating_app:home' %}">Home <span class="sr-only">(current)</span></a> </li> </ul> <!-- Below is login/registration links and the logic--> {% if user.is_authenticated %} Hello, {{ user.username }} <ul class="mylinks"> <div> <li><a href="{% url 'dating_app:profile' user.id %}">My Profile</a></li> <li><a href="{% url 'dating_app:logout' %}">log out</a></li> <div> </ul> <li class="nav-item"> <a class="nav-link" … -
HttpResponseRedirect - How to apply the Python/Django concept to other languages/frameworks
I recently started a Django tutorial at their main site. I noticed that the framework uses HttpResponseRedirect: https://docs.djangoproject.com/en/3.0/intro/tutorial04/ to prevent people from doing two transactions when clicking the browser's back and forward buttons. How do I apply this concept to other frameworks like React. Much appreciated. -
Django renders wrong template
It's really strange issue, but Django renders wrong template. When i try to run my project, it doesn't render template from my template folder, but really old template, that i changed about 100 times now. I even tried to re-download my project from github and open it in PyCharm. Still the same issue. Has anyone ever encountered this? -
Django - automatically save a copy of an object ID to a second table
I want my Django application to also save the ID of a newly created Post object to my Post_Collection table as soon a actual Post object gets created therefor I tryd the following solution which sadly does nothing so far: models.py collectable_post_models = models.Q(app_label='App', model='post_model1') | models.Q(app_label='App', model='post_model2') | models.Q(app_label='App', model='post_model3') class Post_Collection(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content_type = models.ForeignKey(ContentType, limit_choices_to=collectable_post_models, related_name='collections', related_query_name='collection', on_delete=models.CASCADE, null=True, blank=False) object_id = models.CharField(max_length=36, blank=False) content_object = GenericForeignKey('content_type', 'object_id') date_added = models.DateTimeField(auto_now_add=True, blank=False) class Meta: unique_together = ('content_type', 'object_id') verbose_name = "Post Collection - HELPER TABLE" verbose_name_plural = "Post Collections - HELPER TABLE" ordering = ['-date_added'] # currently not working @receiver(post_save, sender=Post) def ensure_post_exists(sender, **kwargs): if kwargs.get('published_date', False): Post_Collection.objects.get_or_create(post=kwargs.get('instance')) I would expect that each time I create a new Post element the ID gets saved to the Post_Collection table also. Thanks in advance