Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : Manipulating a form's csv file input
Issue :- I get an empty rows and header in my custom function. Not able to find the reason. Backdrop of the issue:- I'm working on a django page/form that should take a submitted csv file, and if the 'type' field in the form is checked, it will check if the provided csv has a particular set of columns. Note, all the classes below are in a single module (validations.py). And the csv file which i input is also proper, with rows and headers. Below is just a part of a task where i get the issue.. (And no dependencies, at least for the issue). class ReportTypeValidator: def __init__(self, config_form, brand_form_set): self.config_form = config_form self.brand_form_set = brand_form_set def check(self): is_checked = self.config_form.cleaned_data['type'] if is_checked: self.REVIEW_FILE_COLUMNS_TYPE = REVIEW_FILE_COLUMNS+['Report_Type'] files = self._get_brand_files(self.brand_form_set) print('%%%%%%%%%%%%%') print(files) for file in files: rows, header = FieldFileCsvHelper().read_csv_file(file) print('==========') print(rows) print(header) print(file) missing_columns = get_missing_columns(header, self.REVIEW_FILE_COLUMNS_TYPE) if missing_columns: message = self.message.format(missing_columns=', '.join(missing_columns)) raise ValidationError( message, code=self.code,) else: pass def _get_brand_files(self, brand_form_set): file_list = [] for index, brand_form in enumerate(brand_form_set): file =brand_form.files[f'form-{index}-review_file'] file_list.append(file) print('@@@@@@@@@@@@@') print(file_list) return file_list Before I show further details, please see the django terminal during the above function execution. I added print statements to see the … -
Django: insert multiple input text and file
I have recently tried to learn Django and I want to know it's possible to insert multiple input with this form structure to table database? if it's possible, can you tell me how it is? Thank you!!! <form class="log-in" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div> <input type="text" name="title"> <input type="file" name="image"> </div> <div> <input type="text" name="title"> <input type="file" name="image"> </div> <div> <input type="text" name="title"> <input type="file" name="image"> </div> <button type="submit" class="btn btn-info">Submit</button> </form> -
Bookmark model causing slow data load
so I have a BookmarkBase model that provides bookmarking for different objects: class BookmarkBase(models.Model): class Meta: abstract = True user = models.ForeignKey(Profile,on_delete=models.CASCADE, verbose_name="User") def __str__(self): return self.user.username class BookmarkPost(BookmarkBase): class Meta: db_table = "bookmark_post" date = models.DateTimeField(auto_now_add=True) obj = models.ForeignKey('home.Post',on_delete=models.CASCADE, verbose_name="Post") class BookmarkBlog(BookmarkBase): class Meta: db_table = "bookmark_blog" date = models.DateTimeField(auto_now_add=True) obj = models.ForeignKey('home.Blog',on_delete=models.CASCADE, verbose_name="Blog") Now I have written an Ajax code that whenever user bookmarks and object or has bookmarked the object the button will change (It will go from outlined to fill ). However, in order to check to see if every object is bookmarked by a user I have written a template tag: @register.simple_tag(takes_context=True) def is_bookmarked(context): request = context['request'] id = hashids.decode(context['hid'])[0] if context['t'] == 'post': return BookmarkPost.objects.filter(user__id=request.user.id, obj__id=id).exists() elif context['t'] == 'blog': return BookmarkBlog.objects.filter(user__id=request.user.id, obj__id=id).exists() elif context['t'] == 'buzz': return BookmarkBuzz.objects.filter(user__id=request.user.id, obj__id=id).exists() which then my bookmark.html is {% load ibuilder %} <form class="bookmark-form" method="POST"> {% csrf_token %} {% is_bookmarked as bookmarked %} {% if bookmarked %} <button class="p-0 etbm_btnall no-outline btn btn-md" type="submit" data-url="{% url 'main:add-bookmark' hid=hid obj_type=t %}" > <svg class="bi mr-1 bi-bookmark-fill" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M3 3a2 2 0 0 1 2-2h6a2 2 0 0 1 2 … -
How to install and run django-filer locally?
Pretty new to Django and after following installation steps found on the documentation, I have had not luck. Can someone please guide me through the exact steps so I can run and use the application on my local machine? -
Object of type Cart is not JSON serializable
I have a products model and a cart model. There is a ManyToMany relation that I put in cart model. I am trying to return the object of cart model along with the context dictionary but it is giving this error "Object of type Cart is not JSON serializable". I am using Django version '3.0.7'. I am following Justing Michael's Tutorial,He is using lower Django version and its working on that. Did Django change this thing? class CartManager(models.Manager): def new_or_get(self,request): cart_id = request.session.get('cart_id') qs = self.get_queryset().filter(id = cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new_cart(user = request.user) new_obj = True request.session['cart_id'] = cart_obj return cart_obj,new_obj def new_cart(self,user=None): user_obj = None if user is not None: if user.is_authenticated: user_obj = user return self.model.objects.create(user=user_obj) and the model actually is: class Cart(models.Model): user = models.ForeignKey(User,on_delete = models.CASCADE,null=True,blank=True) products = models.ManyToManyField(Product,blank=True) #more fields -
I hosted my Django based website using ec2 compute and apache server it works fine in ignito mode and not in normal browser window?
I used GoDaddy domain and cloudflare ssl certificate. When i open in normal browser window it give me a json object and work fine in ignito mode. My website : neptuneworld.in Plz let me know what am i missing. -
How can I share a link including a quote from a web page to Facebook post from the Facebook browser?
I have created a web APP using Django that provides quizzes and created a Facebook App for it. When the user finishes the quiz he is asked to share his results to Facebook, when the user pressed the share button I create a Facebook post that includes my website page URL, a thumbnail, and a quote and besides that the Facebook App name also appears in its place in the post as well. I am using the following in the HTML: <a href="https://www.facebook.com/dialog/share? app_id=id &quote={{quote}} &href=http:link &redirect_uri=link " title="Share on Facebook"> <span class="fa fa-facebook-square fa-3x"></span> </a> Everything is working fine in all browsers, but when I practice the quiz in the Facebook browser and press the share button, nothing is passed to the share box from things mentioned above and the share box appears empty! I am new to this so can anyone help me to figure out where is the mistake? -
Why is my Django model missing the values attribute?
I am trying to filter a model by its latest entry and grab all of its values in one fell swoop with .values(). However, the issue is that it doesn't contain the values attributes. I want the values attribute so I can easily serialize the model object's data. Technically speaking, I do have access to my fields directly (i.e., ticket_number.first_name), but this would require me to manually process each field one by one. I've used .filter() several times on previous models that do contain .values(), so why doesn't this specific filter query contain the values attribute? I'm not understanding where or how this query is any different. views.py: ticket_number = TicketForm.objects.filter(customer_name="Bob").latest('ticket_number') # The values attribute doesn't exist here, but at least I can access my fields directly. # Ticket number is the primary key for this TicketForm model. >>> print(ticket_number) 12345 >>> print(type(ticket_number)) <class 'log.models.TicketForm'> -
My static (CSS) files are loading for my Django website, but they are not being displayed. What am I missing or doing wrong?
The settings.py file in the project folder defines the STATIC_URL variable as '/static/' The CSS file is inside the app folder: DjangoProject/shop/static/shop/style.css The {% load static %} is at the top of the HTML template (if I use "staticfiles" instead of "static", I get an error) The CSS file is linked using href="{% static 'shop/style.css' %}" The CSS file loads and is visible when I analyze the "view page source", but the actual CSS is not displayed on the webpage. What am I doing wrong? I'm using Django version 3.0.7 -
could anyone explain what instance attribute is in the ModelForm? [Django]
I need to know why may I need to use instance into ModelForm I read about it in Django document what I understand that it can replace with save() method somehow if that is correct why I have to use it if not how can I use it and why? -
Is storing data in "thread local storage" in a Django application safe, in cases of concurrent requests?
I have seen at many places that using thread local storage to store any data in Django application is not a good practice. But this is the only way I could store my request object. I need to store it because my application has a complex structure. And I can't keep on passing the request object at each function call or class intialization. I need the cookies and headers from my request object, to be passed to some api calls I'm making at different places in the application. I'm using this for reference: https://blndxp.wordpress.com/2016/03/04/django-get-current-user-anywhere-in-your-code-using-a-middleware/ So I'm using a middleware, as mentioned in the reference. And, this is how request is stored from threading import local _thread_locals.request = request And, this is how data is fetched: getattr(_thread_locals, "request", None) So does are the data stored in the threads local to that particular request ? Or if another request takes place at the same time, does both of them use the same data ?(Which is certainly not what i want) Or is there any new way of dealing with this old problem(storing request object globally) -
Equivalent Django query from this SQL query
I try to code the equivalent Django query from this SQL query, but I'm stuck. Any help is welcome. SELECT *, (SELECT count(run.id) FROM runner run INNER JOIN race ON run.race_id = race.id WHERE run.horse_id = r.horse_id AND race.datetime_start < rc.datetime_start ) AS nb_race, (SELECT min(run.chrono) FROM runner run INNER JOIN race ON run.race_id = race.id WHERE run.horse_id = r.horse_id AND race.datetime_start < rc.datetime_start ) AS best_time FROM runner r, race rc WHERE r.race_id = rc.id AND rc.id = 7890 -
Why won't my form post to my home page? Receiving"POST /add/ HTTP/1.1" 302 0 error
I am getting an error when I click my 'Add an Item' button. It's not posting to the home page. "POST /add/ HTTP/1.1" 302 0 I have an add.html template {% extends 'base.html' %} {% block content %} <h2>Add An Item</h2> <hr> <form action="{% url 'add_item' %}" method="POST" class="pure-form"> {% csrf_token %} {{form.as_p}} <button type="submit" class="pure-button">Add Item</button> </form> {% endblock %} I have define my url path path('add/', CreateItem.as_view(), name='add_item'), And I have created my view class CreateItem(CreateView): model = Item fields = '__all__' template_name = 'add.html' success_url = '/' And my index.html has been told to show the table being created {% extends 'base.html' %} {% block content %} <h1>Wish List Items</h1> {% if item_list|length == 0 %} <h3>No Wishlist Items Exist</h3> <hr> {% else %} <table class="pure-table"> <thead> <tr> <th>Description</th> <th>Delete</th> </tr> </thead> <tbody> {% for item in items %} <tr> <td>{{item.description}}</td> <td><a href="{% url 'delete_item' item.id %}">X</a></td> </tr> {% endfor %} </tbody> </table> {% endif %} <a href="{% url 'add_item' %}" class="pure-button">Add An Item</a> {% endblock %} But My table will not show up. Please help. -
How to install mysqlclient on Amazon Linux 2?
I have a Django project and i have deployed it to Elastic Beanstalk Amazon Linux 2 platform. I'm trying to install mysqlclient and add it to requirements.txt file but when i deploy it, i'm getting an error such as; ERROR: Couldn't install package: mysqlclient Package installation failed... I also tried to add a mysql.config file to .ebextensions such as below; packages: yum: python3-devel: [] mariadb-devel: [] but it didn't work either. How can i fix this issue? -
Django: Why is the Urls is different than what it should actually be?
I am Django newbie. I am making a simple login custom system when I press sign-in button if the credential is correct it goes to the welcome page but the URL is http://localhost:8000/login/ I was expecting http://localhost:8000/welcome/ instead Here is my view.py code for login def login(request): if request.method == "POST" : username = request.POST['user'] password = request.POST['psk'] try: user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return render(request, 'welcome.html') else: messages.error(request, 'Username or password didn\'t match.') except auth.ObjectDoesNotExist: print("invalid user") return render(request, 'login.html') the URLs.py of the account app looks as: urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^index/$', home), url(r'^login/$', login), url(r'^logout/$', logout), url(r'^', custreg), ] Please help me and let me know if you need anything else to answer the question -
unable to view file contents in html django - newbie
Please, could you gurus help me solve this to move forward, as a newbie to python and django all my petty tricks failed and couldn't pass this obstacle. Many thanks in advance. I am attempting to build a webpage using django, which runs few python functions/scripts in the backend. To begin, upon accessing 127.0.0.1:8888 I am prompted to input a data (lets say, time in seconds) and then click submit button. Submit button does these two tasks:- runs a python script using subprocess.Popen, which generates a file with naming convention as "results_hhmmss.txt" in folders structured/named as yyyy/mm/dd. irrespective of above task's status, it then opens/renders/redirects to results html page (which is 127.0.0.1:8888/results/) displaying content of "results_hhmmss.txt" file. I have made files urls.py, views.py, welcome.html and results.html but clearly something is not right (as my results filename keeps varying on every run). I have pasted those scripts/code below. Here is my observation of what is not happening to what I expected --- When I click submit, I can see the subprocess executes and file is generated and has data stored in it. Further, the welcome_page (i.e., 127.0.0.1:8888) gets redirected to results page (i.e., 127.0.0.1:8888/results/) But, i do not see contents of … -
What happen in production mode if Django crash?
I'm new to Django. Since in a development environment it happens that an error occurs after a request (often because it is badly handled) and Django crashes, I thought about creating a script (in production) to detect if Django is running and if not run it again (something like this). And of course after adding block try except everywhere. But since Django is well done it wouldn't surprise me if this concern is already taken in consideration, hence my question. Thank you. -
GEOIP_DATABASE setting is defined, but file does not exist error for django-easy-timezones package
I am dynamically trying to change the datetime value in Django templates based on the timezone by using the django-easy-timezones package. I am referring to the link https://pypi.org/project/django-easy-timezones/ However, the moment I run the django application I get the error: GEOIP_DATABASE setting is defined, but file does not exist. How do I resolve this error? -
" Error while running '$ python manage.py collectstatic --noinput" even though I have ny static_root set
So, I already have my static root set, I did manage.py collectstatic so I am not sure what I am doing wrong here. I am trying to push everything to heroku, and I keep getting this error about there not being a path to static files. Am I not providing the correct 'STATIC_ROOT'? I have it as STATIC_ROOT = os.path.join(BASE_DIR, 'static') traceback remote: Traceback (most recent call last): remote: File "manage.py", line 21, in <module> remote: main() remote: File "manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect remote: handler(path, prefixed_path, storage) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 342, in copy_file remote: if not self.delete_file(path, prefixed_path, source_storage): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 249, in delete_file remote: if self.storage.exists(prefixed_path): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 310, in exists remote: return os.path.exists(self.path(name)) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 44, in path remote: raise ImproperlyConfigured("You're using the staticfiles app " remote: django.core.exceptions.ImproperlyConfigured: You're using … -
ModuleNotFoundError: No module named 'graphene_django'
I have been stack with this error for sometime now, I an trying to use Graphene for my graphql Django API but it throws me this error of ModuleNotFoundError: No module named 'graphene_django' File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/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 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'graphene_django' Here is my environment Before you judge 'pip freeze' -
How to fetch a new param inserted by client in request headers using python?
I have a curl request as: curl --location --request POST 'http://127.0.0.1:8000/hit_api/' \ --header 'x-access-token: '' \ --header 'HTTP_APP: "abcd123"' Now I want to obtain the string: abcd123 from the HTTP_APP param inserted by the requester. I tried with: print(request.META) if "HTTP_APP" not in request.META: return JsonResponse({ 'success': False, 'message': 'HTTP_APP not found in Headers' }) And I get only the above JsonResponse because it's not printing the HTTP_APP from the headers. I'm using Django 2.1.2 so cannot use request.headers as per the documentation: https://docs.djangoproject.com/en/3.0/ref/request-response/#attributes Can someone please guide me on how to get the custom header parameter? Thanks -
After deploying django project to heroku, error below shows up if i try to create new user or sign in, I am using the sqlite3 database
relation "auth_user" does not exist LINE 1: SELECT (1) AS "a" FROM "auth_user" WHERE "auth_user"."userna... -
Django access a list element's attribute in Django template
I already know how to access a list element from views to template like this: In .html file {% load index %} {% lists|index:i %} In templatetags/index.py from django import template register = template.Library() @register.filter def index(indexable, i): return indexable[i] However, in my case, each list element contains several attributes which I want to access, like lists[i].attr, now I can only access lists[i] but not lists[i].attr. What can I do? -
django custom login view (login as guest)
i am making an ecommerce an i have a checkout view in that view i have three forms : a login form a guest login form and a billing address form so basically if a user is logged in normally or as guest i am displaying the billing address form in the template 'checkout.html' otherwise i display the login form and the guest login form but these two forms are handled in different views checkout_login and guest_checkout_login so my question is : is it safe to do so ? this is the chekout template : {% if not billing_profile %} <form method="post" action="{% url 'login_page' %}"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.build_absolute_uri }}"> {{ form }} <button type="submit" class="btn btn-default">Submit</button> </form> <form method="post" action="{% url 'guest_login_page' %}"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.build_absolute_uri }}"> {{ guest_form }} <button type="submit" class="btn btn-default">Submit</button> </form> {% else %} <h1>checkout</h1> billing profile:{{billing_profile}} </br> <form method="post" action=".">{% csrf_token %} {{ adress_form }} <button type="submit" class="btn btn-default">Submit</button> </form> {% endif %} {% endblock %} this is the chekout_login view: def login_page(request): form = LoginForm(request.POST or None) next_ = request.POST.get('next') if request.method == 'POST': if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user … -
Is it okay to run Django API server with root permissions?
I am running django server, using gunicorn. Apart from gunicorn, I have a layer of nginx as a load balancer and using supervisord to manage gunicorn. From the perspective of security is it fine to run my gunicorn server with sudo permission? Is there any potential security leak? Also, does it makes any difference if I am a superuser and not running process with sudo permission as in any case I have sudo permissions as the user.