Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
search for files in S3, when given a path
Given a path to S3 bucket, I need to find another file in the same path and work on it as well. I am using Django in Python. I have a model named "HouseList" and a model named "CustomerFile" I am using a function that returns a list of HouseList objects that I need to modify. for each object there, I have a file path, and in that path, I can find the corresponding customer file, as you can see in these prints from the terminal: In [7]: HouseList.objects.get(id=11508).file_path Out[7]: u'85/1545927/omc_emea_hl_small.csv' In [8]: CustomerFile.objects.get(id=5031).file_path Out[8]: u'85/1545927/omc_emea_pos_small.csv' Is there a way, given a prefix of the path, to get a list of all the files that are located there? Thanks. -
make django blog searchable on google
I am trying to develop a django based online publishing platform like - medium but confused about how to index my posts automatically on google. I searched for that but lost in them, and confused how to start and what are best practices for indexing django website on search engines. If anyone can explain full procedure of that like - I read about creating xml sitemap file to improve seo but really can't understand how search engines use it ? I am totally lost where to start. Thanks. -
Page not found error in django application
I am receiving that error when I try to visit the detail page of my post model. I have the slug field in the URL file, but it doesn't seem to matter. Model TYPE_STATUS = ( ('post', 'Post'), ('page', 'Page'), ('media', 'Media'), ('menu', 'Menu'), ) class Post(models.Model): title = models.CharField(max_length=70) slug = models.SlugField(blank=True, unique=True) type_status = models.CharField(max_length=70, default='post', choices=TYPE_STATUS) description = models.TextField() short_description = models.CharField(max_length=155) image = models.ImageField( upload_to=upload_image_path, null=True, blank=True) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) featured = models.BooleanField(default=False) View from django.views.generic import DetailView from django.shortcuts import render from posts.models import Post class home_page(DetailView): queryset = Post.objects.filter(slug='home', featured=True) template_name = "home_page.html" Urls from .views import home_page urlpatterns = [ url(r'^(?P<slug>[\w-]+)/$', home_page.as_view(), name='home'), ] -
Facebook Like Button causing Uncaught DOMException
I'm trying to implement the Facebook like and share buttons and it works fine. However, I noticed many error : <div id="fb-root" class="display_inline"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = '//connect.facebook.net/fr_FR/sdk.js#xfbml=1&autoLogAppEvents=1&version=v3.2&appId=108984935830019'; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="fb-like display_inline" data-href="https://wwww.lamontagnesolitaire.fr{% url 'read' post.id post.title|slugify %}" data-width="100" data-layout="button" data-action="like" data-size="small" data-show-faces="true" data-share="true"></div> Am I missed something ? Thank you -
Link objects through ForeignKey
I have a Post model and I create posts in the admin page of Django through a rich text editor. During post creation I upload local files, media and images. And I want to associate each downloaded file with its current post. For this, the file model has a foreign key pointing to the post. The problem is that in views.py I cannot create the ForeignKey of the file object, since the post associated with it has not yet been created, and the file has already been uploaded. How can I associate a file with a post that has not yet been created. At least after creating the post. I create a post in the admin page and not in a separate page. #My admin.py class PostModelAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("title", )} list_display = ["title", "updated", "created"] list_display_links = ["title"] list_filter = ["created", "tags"] search_fields = ["title", "content",] form = MyTextForm class Meta: model = Post class Media: js = ('//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js', 'js/csrf_setup.js', 'js/tinymce/tinymce.js', 'js/init-tinymce.js',) admin.site.register(Post, PostModelAdmin) #model of Uploaded File class UploadFile(models.Model): file = models.FileField(null=True, blank=True, upload_to='files/%Y/%m/%d/', ) upload_by = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE, related_name="file_author") post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, related_name="file_post") #upload file through jquery Ajax if (meta.filetype == 'file') { … -
How to connect login model and post model
I have created a login and signup model also a post model in which a user can post the title and description. But when I login with a user and create a post then that post is also viewed by other user also. I am using Django(python) with database sql. For sign up form : from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class UserCreateForm(UserCreationForm): class Meta: fields = ("username", "email", "password1", "password2") model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Display name" self.fields["email"].label = "Email address" url.py : from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ url(r"login/$",auth_views.LoginView.as_view(template_name="accounts/login.html"),name='login'), url(r"logout/$", auth_views.LogoutView.as_view(), name="logout"), url(r"signup/$", views.SignUp.as_view(), name="signup"), ] How can I limit my post to that specific user? -
how to create params in django url?
I have a django project where url is like this url(r'^invoice/(?P<invoice_id>[A-Za-z0-9]+)/(?P<order_id>[A-Za-z0-9]+)$',GenerateInvoicePdf,name='invoice'), which generates url localhost:8000/invoice/2341wq23fewfe1231/3242 but i want url to be like localhost:8000/invoice?invoice_id=2341wq23fewfe1231&order_id=3242 i tried documentation and used syntax like this re_path(r'^comments/(?:page-(?P<page_number>\d+)/)?$', comments), But did not get desired result. how can i do so? -
Creating the same query in annotate
I have a query that will get all of user 3's following list. I also want to check if the logged in user is following each of user 3's following list. So for example let's say user 3's following list is: 2,3,4 and the logged in user is following 2 and 4. So the result would be: 2:1, 3:0 and 4:1 1 indicating that the logged in user is following and 0 indicating the logged in user is not following. I'm trying to accomplish this using this query: Following model class Following(models.Model): target = models.ForeignKey('User', related_name='followers', on_delete=models.CASCADE, null=True) follower = models.ForeignKey('User', related_name='targets', on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} is followed by {}'.format(self.target, self.follower) Query User.objects.filter(followers__follower=3).order_by('-followers__created_at').\ annotate(is_following=Count('followers', filter=Q(followers__follower=self.request.user), distinct=True)) However, for some reason the annotate query is not running at all. I think it is because it is the same query as the main query, but with different parameters. How can I make it so that my query works in the way I want it to work? -
Customize djoser logout
Djoser have auth/token/logout/ end point to logout and it destroys the token. Now I wanted to do more when logout so I have inherited the TokenDestroyView of djoser: from djoser.views import TokenDestroyView from djoser import utils class UserLogoutView(TokenDestroyView): def post(self, request): attendance = Attendance.objects.get(user=request.user, check_in_date=localdate(now())) attendance.check_out = localdate(now()) attendance.save() print(attendance) print(attendance.check_out) utils.logout_user(request) return Response(status=status.HTTP_204_NO_CONTENT) Now I have my own endpoint as users/v1/logout/ I get the 200 52 response but it is not deleting the token and even it is not going inside the post method. Where am I missing ? -
How to redirect using a custom django 404 error view?
I want to redirect users to the login page if they enter an invalid url, but I can only figure out how to render the login page without actually changing the url. Is it possible to redirect with handler404 in django? I have the handler404 in my root URLconf and debug mode set to False. Any help is greatly appreciated. -
Where to call a celery task on model save
I need to call a celery task when saving a model. I have conflicting imports that I do not know how to resolve. I am wondering if anyone knows another way I can structure this to avoid conflicting imports models.py from .tasks import celery_task class Picture(PolymorphicModel): file = models.ImageField() processed_file = models.ImageField(blank=True, null=True) ... def save(self, *args, **kwargs): if self.file: self.processed_file = celery_task.delay(self.id, other_arg) super(Picture, self).save(*args, **kwargs) tasks.py from .models import Picture @task def celery_task(id, other_arg): try: picture = Picture.objects.get(id=id) except ObjectDoesNotExist: picture = None if picture: return some_other_function(picture.file) return None -
Changing PostgreSQL server changed Django app characteristics
I had to switch an enterprise Django 1.11 site from a corporate-hosted PostgreSQL 9.4 server to AWS RDS Aurora-PostgreSQL 10 cluster. My initial impression was that it should be a straightforward migration, as I was not using any version-specific code. Immediately after migration, the site started breaking down horribly. Queries that used to take milliseconds suddenly jumped to 100x the time, causing timeouts all over gunicorn threads. I also kept seeing connections being dropped from both RDS and Django. It kept appearing as if it would be some setting I need to match between previous server and current server, but despite engaging PostgreSQL experts and AWS support, there were no simple answers (or even complex ones). I finally had to fine-tune most queries in my Django code to bring stability to the site. The app has several queries that refer to foreign relationships, so I used a number of prefetch_related and similar tricks to fix the slowdown. So, a query that was taking 0.5 seconds went to 80 seconds, and after I added prefetch_related, went back to 0.5 seconds. Even though the site is now stable, I am posting this in the hope that some PostgreSQL and/or Django expert sees … -
Django REST - Can't access my edit page for my API
So I have a code that lists all my posts in the API and it is doing what it is supposed to be doing. However, the code to edit the details of every posts wasn't working. What I am trying to do is that if I access the url for the post that I want to edit, I should be able to. But for some reason I can't. I thought I was doing the right thing. I was trying to access the posts by their ids through the urls. My codes are down below. views.py # To retrieve and list all posts class ListPosts(generics.ListCreateAPIView): queryset = Posts.objects.all() serializer_class = PostsSerializer # To view the details of the listed posts class DetailPosts(generics.RetrieveUpdateDestroyAPIView): queryset = Posts.objects.all() serializer_class = PostsSerializer urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^', views.ListPosts.as_view(), name="list_posts"), url(r'^(?P<post_id>\d+)/$',views.DetailPosts.as_view(), name="detail_posts"), ] -
Pylint not working despite installation in a virtual environment
I'm a newbie in Django and I've been trying to setup pylint in my virtual environment on Vscode. During the installation I made sure that I was in my virtual environment as well as had the virtual environment python interpreter selected. Method used to install : /home/nived/Documents/BTRE_PROJECTF/venv/bin/python -m pip install -U pylint This is the log if it does matter : Collecting pylint Using cached https://files.pythonhosted.org/packages/a5/06/ecef826f319055e6b231716730d7f9047dd7524ffda224b521d989f085b6/pylint-2.2.2-py3-none-any.whl Collecting astroid>=2.0.0 (from pylint) Using cached https://files.pythonhosted.org/packages/fc/53/8809bc008bad0300897281a7b320b286dc0e84e836396c0cff6279841e8a/astroid-2.1.0-py3-none-any.whl Collecting isort>=4.2.5 (from pylint) Using cached https://files.pythonhosted.org/packages/1f/2c/22eee714d7199ae0464beda6ad5fedec8fee6a2f7ffd1e8f1840928fe318/isort-4.3.4-py3-none-any.whl Collecting mccabe (from pylint) Using cached https://files.pythonhosted.org/packages/87/89/479dc97e18549e21354893e4ee4ef36db1d237534982482c3681ee6e7b57/mccabe-0.6.1-py2.py3-none-any.whl Collecting typed-ast; python_version < "3.7" and implementation_name == "cpython" (from astroid>=2.0.0->pylint) Using cached https://files.pythonhosted.org/packages/de/50/7571200eff27c5c30dafa595e355495e1de85aad5fa3fe4c206791d827ff/typed_ast-1.1.1-cp36-cp36m-manylinux1_x86_64.whl Collecting lazy-object-proxy (from astroid>=2.0.0->pylint) Using cached https://files.pythonhosted.org/packages/65/1f/2043ec33066e779905ed7e6580384425fdc7dc2ac64d6931060c75b0c5a3/lazy_object_proxy-1.3.1-cp36-cp36m-manylinux1_x86_64.whl Collecting wrapt (from astroid>=2.0.0->pylint) Collecting six (from astroid>=2.0.0->pylint) Using cached https://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whl Installing collected packages: typed-ast, lazy-object-proxy, wrapt, six, astroid, isort, mccabe, pylint Successfully installed astroid-2.1.0 isort-4.3.4 lazy-object-proxy-1.3.1 mccabe-0.6.1 pylint-2.2.2 six-1.12.0 typed-ast-1.1.1 wrapt-1.10.11 settings.json in the .vscode file contains the following code : { "python.pythonPath": "venv/bin/python" } Despite all this. The linter does not work and I'm not notified of any errors. -
Django template url not correctly getting parameter
I am able to print the correct object pk in the template using a template tag, but when I use the same code in a url parameter it does not show up. I am trying to using the first result pk from a many to many relationship to create a url parameter to link to that page. It works when I manually input the pk, but when I use category.quote_set.first.pk it does not work. "category" is is queryset of all categories, which have a many to many relationship to quotes. <p>{{ category.quote_set.first.pk }}</p> <p><a href="{% url 'mottos:quote' category.quote_set.first.pk %}"></a></p> The url file has path('motto/<int:pk>/', views.QuoteView.as_view(), name='quote'), -
Image zoom/magnify using javascript plugin, in django framework
I have a hard time incorporating a magnifying javascript plugin feature. Basically, I was able to run this plugin on a static html template with static images. but I can't seem to run it at all on my django built website. <!DOCTYPE html> <html> <head> <title>Items</title> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=Edge;chrome=1" /> <title>EasyZoom, jQuery image zoom plugin</title> <link rel="stylesheet" href="css/example.css" /> <link rel="stylesheet" href="css/pygments.css" /> <link rel="stylesheet" href="css/easyzoom.css" /> </head> <body> {%if entry.image_set.get.imgfile%} <!-- images are extracted from the entry model --> <div class="easyzoom easyzoom--overlay"> <a href="{{MEDIA_URL}} {{entry.image_set.get.imgfile.url}}"> <img src="{{MEDIA_URL}} {{entry.image_set.get.imgfile.url}}" alt="Green-SLI" /> </a> </div> {%endif%} <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="dist/easyzoom.js"></script> <script> // Instantiate EasyZoom instances var $easyzoom = $('.easyzoom').easyZoom(); // Setup thumbnails example var api1 = $easyzoom.filter('.easyzoom--with-thumbnails').data('easyZoom'); $('.thumbnails').on('click', 'a', function(e) { var $this = $(this); e.preventDefault(); // Use EasyZoom's `swap` method api1.swap($this.data('standard'), $this.attr('href')); }); // Setup toggles example var api2 = $easyzoom.filter('.easyzoom--with-toggle').data('easyZoom'); $('.toggle').on('click', function() { var $this = $(this); if ($this.data("active") === true) { $this.text("Switch on").data("active", false); api2.teardown(); } else { $this.text("Switch off").data("active", true); api2._init(); } }); </script> </body> </html> My images are located inside entry model, and they are extracted from there. Does that have an impact on whether the magnify script will work or not? Since they … -
How to redirect to 'http://127.0.0.1:8000/profile/' instead of 'http://127.0.0.1:8000/accounts/login/?next=/profile/'
I'm trying to edit user profiles. The user edits a form on profile.html and when they submit it, they should be redirected back to profile.html (the same page). Even though I changed my LOGIN_REDIRECT_URL, I'm still redirecting to accounts/login (the default). views.py @login_required def profile(request): user = request.user if request.method == "POST": signupform = SignUpForm(data=request.POST, instance=request.user) if signupform.is_valid(): signupform.save() return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) return render(request, 'profile.html', "context stuff here") settings.py LOGIN_REDIRECT_URL = '/profile' urls.py url(r'^profile/$', views.profile, name='profile') How can I successfully redirect to profile.html? -
timedelta between 2 input Fields
first of all thanks for your time. A basic reservation system I need to input 2 dates (2 fields on models) and get the difference between them, then it should output this difference, in days multiplied by a constant if less then 3 or other constant if more than it. I've tried a lot of questions from here and read the datetime and timedelta doc but im not getting succes with timedelta. Those are my models: class Visitante(models.Model): Nome = models.CharField(max_length=30) Data1 = models.DateField(blank=True) Data2= models.DateField(blank=True) RG = models.CharField(max_length=9) and those are my views: def reserv (request): tdelta = timedelta(days = 30) d1= Visitante.Data1 d2= Visitante.Data2 delta= tdelta (d1 - d2) return render(request, 'reserv-form.html', { 'date': delta }) then im getting this error: TypeError at /reservas/reserv-form/ unsupported operand type(s) for -: 'DeferredAttribute' and 'DeferredAttribute -
Django and React getting 403 forbidden
I've used create-react-app combined with Django Rest Framework to make a small site. Everything works perfectly when I use npm start and hit the Django API from one port to another. When I npm build the static react files and serve them from within the Django app, however, I get 403 forbidden when hitting a number of endpoints. I think it has something to do with CSRF, but I can't figure out what. I serve the static files from views.py: @api_view(['GET']) def serve_html(request): try: with open(os.path.join(REACT_APP_DIR, 'build', 'index.html')) as f: return HttpResponse(f.read()) except FileNotFoundError: return HttpResponse( """ This URL is only used when you have built the production version of the app. Visit http://localhost:3000/ instead, or run `yarn run build` to test the production version. """, status=501, ) My urls.py contains the catchall for the static files at the bottom: urlpatterns = [ # ..all api paths url(r'^', serve_html, name='serve_html'), ] I use TokenAuthentication and SessionAuthentication: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } And the api requests that require users to be logged in have the following decorators: @authentication_classes((SessionAuthentication, TokenAuthentication)) @permission_classes((IsAuthenticated,)) Sorry for the open-endedquestion, but I'm at my wit's end here; I really don't know why it's … -
Use one models data in the creation of another model
Say you allow a user to add a Book model to your library database. However you don't want them to add a Genre model to the Book. You have a Genre model in your database already with all listed Genres in the world. When the user adds a Book to your database, you want your database to add the proper genre based on text in the Book's summary. Say the book's summary has the word science and fiction in it when it's created. The database will then add a Genre of science fiction to your book wither at the moment of Book creation or immediately after Book creation. I am trying to do this same thing with adding Workout's to a database and having movement types added to them after creation. Such as: I add a Workout as shown (using a textfield): 5 rounds of: 15 Pull Ups 30 Squats 200m Run I then want the database to create 'tags' associated to this workout by reading the workout and tagging the correct Movement model: Pull Up, Squat, and Run. This way I can search the database by workouts that contain pull ups, squats, or runs and this workout will show … -
Create csv from db data in django project
I have one django project and want to create one csv file from the data in html(xxx) table by clicking the button in html template. What should the code be look like to fulfill such function? Here's the view.py, Model and html template of my project. Really thanks! Html: Html(xxx): <table> <tr> <th><div class="panel-heading">No.</div></th> <th><div class="panel-heading">Search Content</div></th> <th><div class="panel-heading">Title</div></th> </tr> <tr> {% for i in datas %} <td><div class="panel-body"><small>{{forloop.counter}}</div></td> <td><div class="panel-body">{{ i.0 }}</div></td> <td><div class="panel-body">{ i.1 }}</div></td> </tr> </table> view.py: def table(request): user = request.user data = Outputting.objects.filter.order_by('batch_id').values_list('col_a1', 'col_b1') return render(request, "xxx.html", {"datas": data}) Model: class Outputting(models.Model): date_added = models.DateTimeField(default=timezone.now) batch_id = models.AutoField(primary_key=True) col_a1 = models.CharField(max_length=1000) col_b1 = models.CharField(max_length=1000) After click the button, csv could be generated automatically. -
Django on AWS Elastic Beanstalk - No module named MySQLdb Error
I have been using AWS Elastic Beanstalk to run this web app for a while with no issues on Amazon's Linux version Python 2.7 running on 64bit Amazon Linux/2.0.1. When I tried to "upgrade" to the latest Amazon Linux version: Python 2.7 version, Linux/2.7.7 or any version after 2.0.1, I get this error: ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb. Did you install mysqlclient or MySQL-python? I do have both installed and included in my requirements.txt file MySQL-python==1.2.5 mysqlclient==1.3.14 I tried reinstalling them both and removing them one or the other from the requirements but still no luck. Any ideas? What did have change since everything is working correctly on version 2.0.1 and it is not working on any newer EB version? -
What is the purpose of these LoginRequiredMixin's attributes in Django 2.0?
I am trying to understand how to implement LoginRequiredMixin in my CBV (Class Based View), but I don't understand the purpose of these attributes; LoginRequiredMixin attributes: login_url = settings.LOGIN_URL redirect_field_name = REDIRECT_FIELD_NAME raise_exception = False Note: There is a website that I looked for; https://django-braces.readthedocs.io/en/v1.2.0/access.html#loginrequiredmixin -
Run python in a html template while iterating though a list
def ViewCharges(request): account = get_object_or_404(StripeAccount, team_members=request.user) payment_requests = PaymentRequest.objects.filter(company=account).order_by('-created') return render(request, 'dashboard/charges.html',{'payment_requests':payment_requests}) This is how my template looks after doing {% for request in payment_requests %} <tr> <td>{{ request.name }}</td> <td>{{ request.email }}</td> <td>{{ request.amount }}</td> <td>{{ request.paid }}</td> <td><a href="/dashboard/charges/{{ request.pk }}" class='btn btn-dark btn-sm'>Manage</a></td> </tr> {% endfor %} And in my models, I store the paid field in pence (e.g 100 = £1), this is for stripe. And I can properly format it by doing real_amount = "{:.2f}".format(amount / 100) this works fine until I need to do it in a for loop in html, is there a way I can do this in the html doc <tr> <td>Bob</td> <td>Bob@example.com</td> <td>£20</td> <td>Yes</td> <td><a href="/dashboard/charges/3523" class='btn btn-dark btn-sm'>Manage</a></td> </tr> The rest is fine I just need some help with that formatting, does anybody have any suggestions? -
Django rest framework TokenAuthentication custom `obtain_auth_token` view not authenticating user
Here is my situation: I am using the django rest framework with TokenAuthentication. Everything works as expected, except the login call, where the client sends credentials to authenticate, and receives the token.key value associated with the authenticating user. Every call to login a user returns status=400 content='{"non_field_errors":["Unable to log in with provided credentials."]}' This indicates that the call to django.conf.auth.authenticate() in the TokenAuthentication serializer returned None rather than a valid user. Pertinent details: I made a slight modification to the built-in ObtainAuthToken class, and the AuthTokenSerializer class to facilitate logging users in with email + password rather than username + password. I also changed the way User objects are created, so that passwords are not passed back to the client. I know it's a hashed value, and will be using SSL, but I still find it unnecessary. I suspect I am doing something wrong in the second modification, as I'm fairly certain the thing that isn't working the way I expect it to is the call to authenticate() in the AuthTokenSerializer. Any help would be greatly appreciated!! Here are the relevant files: Abbreviated settings.py INSTALLED_APPS = [ # included middleware 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # extra middleware 'rest_framework', …