Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to filter date in template django , current time in the template
i need to filter my date column in the template , {% if obj.date__gte=timezone.now %} <td class='red'>{{obj.date}}</td> {% else %} <td>{{obj.date}}</td> {% endif %} is it possible to do something like that inside the template?! thanks -
At what stage should coverity static analysis be done?
When should we do coverity static analysis (no build, buildless capture since we don't use compiled language) in our CI lifecycle? We have stages like test, build, deploy. What are the pros and cons of different approaches? This is for a django application which is deployed onto kubernetes. test stage involves testing django end-points. build stage involves building a docker container deploy stage involves rolling out the recently built docker image -
OperationalError: no such table: Student
I am learning Python and Django. Currently I have a bit of trouble here. My app I ran appeared with this error "OperationalError: no such table: Student". Can someone help me with what is going wrong. Thank all. Error: enter image description here Models.py: enter image description here Urls.py: enter image description here views.py: enter image description here Settings.py enter image description here -
Web Page with div class= parallax_background parallax-window is not loading in django/ pycharm
I am configuring a webpage using django and pycharm. I have placed all the static files and made the changes in settings.py file. In html i have added load static block at the beginning and added static block to all urls. Now when I run the server, all the static content is loading properly except two blocks (testimonial and footer) having div class= parallax_background parallax-window All files are shared at below location in below google drive -- https://drive.google.com/drive/folders/1mgIesxx8Kat42qOourcPQvFWL_iS2D43?usp=sharing Any help would be appreciable. -
uploading a image from django to sql server
Hi i am new to web development and sorry for wrong key words. there is a table present in the sql server created as following which will store image CREATE TABLE [dbo].[FileStorage]( [StorageID] [uniqueidentifier] NOT NULL, [BinaryData] [image] NOT NULL, CONSTRAINT [PK_Storage] PRIMARY KEY CLUSTERED ( [StorageID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO I host the angular from our django application copied the UI build to static folder of my django application. i have never created module, i usually run sql commands in view to execute the query. Now i am in bit of a situation where user selects a image from the UI, i need to take that image pass it to django(How?) then from django application i should pass the image to sql server and store that image. next time i need to fetch that image and display in the UI when clicked. How do i do that? -
Django site not updated
I got my django app configured with AWS S3 and all the media files are hooked up correctly. When I post a new article, the media files are stored in S3 and everything seems to work fine. After about 5 hours, I checked the site and it was back to a time frame where the article was not posted. This means it went back in time and got regressed to an earlier code? I don't know what is happening, and why after many days of testing it goes back to that one stage. Any advice? -
Django, twitter app, like/dislike feature for all the tweets:
As in title, i write a tweet-like app and i already have a feature for like/dislike each tweet. It works, but this is only for one tweet per page, like: <form action="{% url 'like_tweet' tweet.id %}" method="post"> {% csrf_token %} {% if is_liked %} <button type="submit" name="tweet_id" value="{{ tweet.id }}" class="btn btn-danger">Dislike</button> - {{ total_likes }} Likes {% else %} <button type="submit" name="tweet_id" value="{{ tweet.id }}" class="btn btn-primary">Like</button> - {{ total_likes }} Likes {% endif %} </form> With the view: class TweetDetailsView(View): def get(self, request, tweet_id): tweet = Tweet.objects.get(id=tweet_id) is_liked = False if tweet.likes.filter(id=request.user.id).exists(): is_liked = True stuff = get_object_or_404(Tweet, id=self.kwargs['tweet_id']) total_likes = stuff.total_likes() return render(request, "twitter/tweet.html", locals()) How can i obtain this same result for all the tweets in one html, like: {% if user.is_authenticated %} {% for t in tweets %} <table class="table1"> <br> <tr> <td> @{{t.user}} <br> <br> {{t.content}} <br> <br> {{t.creation_date}} <br> <br> <a href="{% url 'reply_to_tweet' t.id %}">Reply</a> <br> <br> <a href="{% url 'tweet' t.id %}">Details</a> <br> <br> <form action="{% url 'like_tweet' t.id %}" method="post"> {% csrf_token %} {% if is_liked %} <button type="submit" name="tweet_id" value="{{ t.id }}" class="btn btn-primary btn-sm">Dislike</button> - {{ t.total_likes }} Likes {% else %} <button type="submit" name="tweet_id" value="{{ t.id }}" … -
Styling Django Forms (Django-Countries)
I'm trying to place the form in the center but it doesn't seem to work. I have tried out inserting {{countries}} inside a div but still, it doesn't work. I'm sorry if this is such a dumb question but I don't have someone else to ask to. I know I'm doing something wrong in here but I can't quite pinpoint where is it I'm going wrong at. Thank you in advance! models.py from django.db import models from django_countries.fields import CountryField class CountryChoice(models.Model): name = models.CharField(max_length=100) country = CountryField(blank_label='Global') forms.py from django.db import models from django_countries.fields import CountryField class CountryChoice(models.Model): name = models.CharField(max_length=100) country = CountryField(blank_label='Global') html & css <form id="choices" action="post"> <div class="sample"> {{ countries }} </div> <button>Submit</button> </form> form .sample { align-items: center; } -
How to store and display files and hyperlinks in angular + django application hosted on cloud foundry using sql server database
Hi I have question on possible ways of implementing file storage and retrieval in angular and django based application hosted on sql server. I have an application which is hosted on Cloud foundry and uses angular for UI and Django for APIs. The database being used is SQL Server. I need to implement a feature in which users can add their hyperlinks/files and can view the same at any point of time after addition. Currently I see an application with similar feature, in the database I could see the Hexadecimal values stored for the files/hyperlinks. In my understanding the UI should send the filepath to the API. And the API should run the SQL query like: INSERT INTO myimages values (1, (SELECT * FROM OPENROWSET(BULK N'FILEPATH', SINGLE_BLOB) as T1)) This should save the file as hexadecimal values. For displaying the file on user click on its name in UI, this stored haxadecimal values should be sent to UI. Is this appropriate way of implementing this functionality? What could be approach to achieve the same. Thanks -
How To Increase GPU Memory Usage With Celery Task?
I start a Celery worker : celery worker -A my_task -l info --pool=solo --concurrency=4 but my nvidia-smi shows this process memory usage only 2.5GB, But I gave 16GB memory so, my process is very slow, how can I use whole memory or I can't setup limit? -
Deploying in Pivotal Cloud Foundry
I deployed my django application in pcf. I am using media directory to store files. Second time when I pushed my changes the old media directory files in pcf is not found. I want the old media files to be retained when the changes are pushed. -
Django Admin 404 - Media URLs?
I understand that this question has been asked previously, however every solution i have found does not fix my problem. In "admin" when saving a model it returns 404. Any model without an image upload is fine. Raised by: django.contrib.admin.options.add_view My settings.py contains: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' #and, in processors: 'django.template.context_processors.media', and my urls.py contains: urlpatterns = [ # urls ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In the model: coat_of_arms = models.ImageField(upload_to='coat_of_arms', null=True, blank=True) -
Display a form field only when a specific value is selected
How to make it possible form.gender field only display when a 'Lost Person' is selected from form.category through dropdownlist which is getting from a category table...................... index.html <form method="post" enctype="multipart/form-data" id="personForm" data-cities-url="{% url 'ajax_load_areas_products' %}" novalidate > {% csrf_token %} <div class="row"> <div class="col-md-3"> {{ form.category | as_crispy_field }} </div> <div class="col-md-3"> {{form.product|as_crispy_field}} </div> </div> <div class="row"> <div class="col-md-6" > {{ form.title | as_crispy_field }} </div> <div class="col-md-6"> {{ form.gender | as_crispy_field }} </div> </div> <div class="row"> <div class="col-md-6"> {{ form.description | as_crispy_field }} </div> <div class="col-md-6"> {{ form.photo | as_crispy_field }} </div> <div class="col-md-6"> </div> </div> <button class="btn btn-secondary btn-block mt-4" type="submit">Submit Post</button> </form> views.py def PostCreate(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() return redirect('dashboard') else: form = PostForm() return render(request, 'chained/post_form.html', {'form' : form}) -
is django better or node for backend? [closed]
I want to expand my skills to backend development, so I want to know which is better to learn Django or node given that I don't have problem with learning python and I already know javascript -
How can I show select dropdown value in django template?
I'm trying to achieve how to get a dropdown value to change the data showing in my page: Here's an photo from my page: here's my views.py: def index(req): test = [ {"name": "hello", "age": 30, "size": 100}, {"name": "ewefef", "age": 12, "size": 32}, {"name": "12d1", "age": 13, "size": 123}, {"name": "dsf", "age": 54, "size": 324}, {"name": "gfd", "age": 1, "size": 12}, {"name": "vcb", "age": 3, "size": 3}, {"name": "csd", "age": 4, "size": 1}, {"name": "a", "age": 32, "size": 11}, {"name": "wfwef", "age": 123, "size": 33}, ] context = { 'test': test, } return render(req, 'index.html', context) here is my template index.html: <select name="pick" id="mySelect"> <option value="name">name</option> <option value="age">age</option> <option value="size">size</option> </select> {% for i in test %} <div id="demo">{{i.name}}</div> {% endfor %} I want to achieve when I select name it will show the name, and when I select age it will show only age... how can I do that? -
How to solve AJAX not Getting JSON response from working URL?
I am using Django, I am trying to generate a JSON response from the views.py file to be received using AJAX. the code of AJAX in my html page is as follows: <script> $( document ).ready(function() { console.log("Inside the jQuery") var chart_data_entry = { 'item':[], 'value':[] }; console.log("Done with chart_data_entry") var objID = "{{plotID}}"; console.log("ObjID " , objID) var Json_Data = "/crm/GenerateChartData/" + objID + "/"; console.log("Json_Data ", Json_Data) $.ajax({ method:"GET", url: Json_Data, success: function(response){ console.log("RESPONSE => ",response) ; }, error: function (error_message) { console.log("Error: " + error_message); } }); }); Everything is working fine, the JSON Response sent from crm/GenerateChartData/All/ is functional, the only problem is that AJAX is not GET-ing from the url (crm/GenerateChartData/All/) and it is jumping straight to the error message, which I can't read because it says " Error: [object Object] " -
Wagtail: Add method to PageModel to get an inspect url
I am trying to add a dynamic instead of a hard coded get_inspect_url method to a PageModel: class MyModel(Page): # ... # this is what I have now, which breaks in prod due to a different admin url def get_inspect_url(self): inspect_url = f"/admin/myapp/mypage/inspect/{self.id}/" return inspect_url I know that you can use the ModelAdmin.url_helper_class in wagtail_hooks.py to get admin urls for an object, but I can't figure a way to do the same on the model level as a class method. Is there a way? -
'dict' object has no attribute 'iterkeys' in django python
i'm not using this method as i know this method will not work in python 3 "params.iterkeys()" but error show 'dict' object has no attribute 'iterkeys'.Although i'm using params.keys() instead of params.iterkeys() params_string = [] for key in sorted(params.keys()): if "REFUND" in params[key] or "|" in params[key]: respons_dict = {} exit() value = params[key] params_string.append('' if value == 'null' else str(value)) return '|'.join(params_string) -
Javascript is not connecting to python Django HTML while CSS is connecting successfully
In my python Django project, HTML template CSS is connecting but js is not. I have connected them by same way, but I don't know why js is not working :( this is the line that I am connecting CSS to HTML <link rel="stylesheet" href="{% static 'main/style.css' %}"> and this the js connecting line <script src="{% static 'main/index.js' %}" defer></script> in my index js file, I have called alert function to know if js is working or not and I can't see that alert message. -
Cookie not being set on angular client
I have a backend app in django python and it is being served on http://localhost:8000. I have a angular frontend which is being served on http://localhost:4200. I have disabled CORS on django. On hitting the login api on http://localhost:8000/auth/login/, I am getting a valid response along with the Set-Cookie header. Here is my angular code to print the cookies: this.http.post<any>('http://localhost:8000/auth/login/', this.LoginForm, { observe: 'response' }).subscribe(response => { console.log("response is ", response); var cookies = this.cookieService.getAll();//('cookies'); console.log("cookies is :", cookies); It prints an empty object on console. How do I make this work? I want to use cookies for authentication. -
Creates a form for registration of two types of users[Django]
I want to create a form for two types of users. Profile and Artisant Profile* coming soon from AbstractUser. Artisant has an ONETOONE relationship with Profile models. but I have the following error: File "/media/wafistos/Projets/YaTache_projet/YaTache/Accounts/views.py", line 17, in sign_artisant profile = form_p.save() TypeError: save() missing 1 required positional argument: 'user' This my models.py models.py picture = models.ImageField(default='default.jpg', upload_to='picture/') adress1 = models.CharField(max_length=255) adress2 = models.CharField(max_length=255) wilaya = models.CharField(max_length=255) code_wilaya = models.CharField(max_length=50) codezip = models.CharField(max_length=50) phone = models.CharField(max_length=50) def __str__(self): return self.username class Artisant(models.Model): Peintre = 'Peintre' Plombier = 'Plombier' PROFESSION = [ (Peintre, 'Peintre'), (Plombier, 'Plombier'), ] user_artisant = models.OneToOneField(Profile, on_delete=models.CASCADE) profession = models.CharField(max_length=200, choices=PROFESSION, default='Artisant') descriptions = models.TextField() def __str__(self): return f'{self.user.username}-[{self.profession}]' forms.py class SignupForm(UserCreationForm): username = forms.CharField(max_length=30) first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) picture = forms.FileField() adress1 = forms.CharField(max_length=255) adress2 = forms.CharField(max_length=255) wilaya = forms.CharField(max_length=255) codezip = forms.CharField(max_length=50) code_wilaya = forms.CharField(max_length=50) phone = forms.CharField(max_length=50) email = forms.EmailField(max_length=200) password1 = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(widget=forms.PasswordInput) class Meta: model = get_user_model() fields = ('email', 'username', 'last_name', 'first_name', 'password1', 'password2', 'first_name', 'last_name', 'picture', 'adress1', 'adress2', 'wilaya', 'code_wilaya', 'email', 'codezip','phone', ) def save(self, user): user.username = self.cleaned_data['username'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.password1 = self.cleaned_data['password1'] user.password2 = self.cleaned_data['password2'] user.email = self.cleaned_data['email'] user.picture = … -
how I can set the time under which user can delete or update it
I have model Order class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) shop = models.ForeignKey(Shop, models.CASCADE, null=True) customer = models.ForeignKey(Customer, models.CASCADE, null=True) product = models.ForeignKey(Product, models.CASCADE, null=True) quantity = models.CharField(max_length=30, null=True, ) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS, default='Pending') note = models.CharField(max_length=1000, null=True) how I can create it if the user is customer then they delete or update under the 5 minutes of order if the user is shop then they can update or delete any time -
Two django generic Class Based Views into the same template
I have been researching on how to render a single template using two class based views and I have not found any material addressing the same. For instance the home.html template with a functionality of creating a new post and at the same time listing all the posts in the database. How do I implement such functionality. class BlogCreateView(CreateView): model = Post template_name = 'home.html' fields = ['title', 'body'] class BlogListView(ListView): model = Post template_name = 'home.html' -
Django, homepage always showing on sub pages
I'm having a problem where the main page is still showing even when redirecting onto the registration page. Any help or guesses on what might cause the problem would mean a lot! Beneath is the main/urls.py file: from django.conf.urls import url, include from . import views app_name = "main" urlpatterns = [ url("", views.homepage, name="homepage"), url("register/", views.register, name="register"), ] The main apps url.py file: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url('tinymce/',include('tinymce.urls')), url('', include('main.urls')), ] The main/views.py file: from django.shortcuts import render from django.http import HttpResponse from .models import ParkingSpot from django.contrib.auth.forms import UserCreationForm # Create your views here. def homepage(request): return render(request = request, template_name = "main/home.html", context= {"parkingspots": [i for i in ParkingSpot.objects.all() if i.parkingspace_id == 1]}) def register(request): form = UserCreationForm return render(request, "main/register.html", context={"form":form}) My html files look the following. First the header file, that all other pages extends. <head> {% load static %} <link = href="{% static 'tiny/css/prism'%"} rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> </head> <body> <nav class="nav-extended"> <div class="nav-wrapper"> <a href="/" class="brand-logo">Steelseries Parking</a> <a href="/" data-target="mobile-demo" class="sidenav-trigger"><i class="material-icons">menu</i></a> <ul id="nav-mobile" class="right hide-on-med-and-down"> <li><a href="/">Main</a></li> <li><a … -
Proxy model django from package
I have a problem in my code from mailbox import Message from django.db import models from django.conf import settings class MyMessage(Message): class Meta : Proxy = True def creattask(self): task = Task(title=self.subject) class Task(models.Model): title = models.CharField(max_length=256) i want to fill title attribut of Task model from subject Message model. for that i use createtask function . but when i go to admin page i found Task(title) model empty !! any help please !!