Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django URL converters for date/time values
I'm trying to use the URL converters built into Django to convert a date time string in the URL into a date object in my views. They work as expected if I enter the URL manually, but trying to generate a URL for it cannot find a match. My converters are simple: from django.utils.timezone import datetime from datetime import time class DateConverter: regex = '[0-9]{4}-[0-9]{2}-[0-9]{2}' def to_python(self,value): return datetime.strptime(value,"%Y-%m-%d") def to_url(self,value): return value.strftime("%Y-%m-%d") class TimeConverter: regex = '[0-9]{4}' def to_python(self,value): t = datetime.strptime(value,"%H%M") return time(t.hour,t.minute) def to_url(self,value): return value.strftime("%H%M") In my template I have some nested loops that are cycling through available time slots where I call url for each combination of time slots: <a href="{% url 'club_boats:trip_booking' trip_date slot.slot.start_time slot.slot.end_time boat.boat.pk %}">Join</a> My urls.py file is: from django.urls import path, register_converter from . import converters, views register_converter(converters.DateConverter, 'date') register_converter(converters.TimeConverter,'time') urlpatterns = [ path('<int:boat_id>',views.detail,name='detail'), path('<date:trip_date>/',views.day_view,name='day_view'), path('<date:trip_date>/<time:trip_start_time>/<time:trip_end_time>/<int:boat>/',views.trip_booking,name='trip_booking'), path('', views.day_view, name='day_view') ] I've confirmed that the data types match what it's expecting (time, datetime, etc...) but the reverse conversion doesn't seem to be happening. When I try to load the tempalte that contains the above url call I get a NoReverseMatch error: Reverse for 'trip_booking' with arguments '(datetime.datetime(2019, 7, 1, 0, 0), … -
URL sent to Django using AJAX is different when printed from Django
I have a JQuery event that, when a link is clicked, an AJAX POST request is sent to a Django function. There I print the recieved url and do other stuff with it. However, when it is printed (by Django) some characters in the url are changed. The specific url this happened with was : https://www.catholicleague.org/05press_releases/quarter%204/051110_put_on_notice.htm Which was printed as : https://www.catholicleague.org/05press_releases/quarter+4/051110_put_on_notice.htm Where %20 was changed to + Here is the AJAX and Django code: $("a").on("click", function(e){ e.preventDefault(); if(e.target.href){ let clicked_source = e.target.href; let csrf_tok = parent.document.getElementById("csrf_tok").value; $.ajax({ url: "/change_origin/", data: JSON.stringify({"clicked_source":clicked_source}), type: "POST", beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrf_tok );}, success: function(response) { console.log(response.msg) }, error:function(error) { console.log(error); } }); } }); def change_origin(request): if request.method == 'POST': received = ast.literal_eval(request.body.decode()) print(received) clicked_source_url = received['clicked_source'] return JsonResponse({'msg': "ok"}) Where decode is used as the JSON object is received in Python as a byte-like object. And ast is used to turn the string representation of the object to an actual object (or dict) for access. I need either: 1) A way to just send a string from Ajax to Django 2) A better way to deal with the received object as I believe using .decode() might be the one … -
Why did the server send me a font that is already installed on my machine?
I am new to web development and I am trying to make a simple web game using python 3.7 with django as web framework combined with the channels package for using web sockets. I am trying to use custom fonts for the game UI. I used the css local() function to make sure the fonts aren't sent if the client has them already installed on his system as it says here: It's common to use both url() and local() together, so that the user's installed copy of the font is used if available, falling back to downloading a copy of the font if it's not found on the user's device. However, it seems that the django development server sends me those fonts although I already have them installed on my machine. Here's my html templates and css: core/templates/core/base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% if title %} <title>Stratego - {{ title }}</title> {% else %} <title>Stratego</title> {% endif %} <link rel="stylesheet" href="{% static "core/css/style.css" %}"> </head> <body> {% block content %}{% endblock %} </body> </html> core/templates/core/game.html: {% extends "core/base.html" %} {% load static %} {% block content … -
"how to get already exist cart id in django"
"when user login into website ,cart_id created without user name and then user jump into cart.html user name stored in cart_id.after that user add and delete item from cart table.but when user was logout form website and again login into website, new cart_id created and the user's cart appears empty" "I want already exist cart and cart item" Models.py class CartManager(models.Manager): def new_or_get(self,request): cart_id = request.session.get("cart_id",None) 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(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj , new_obj def new(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) class Cart(models.Model): user = models.ForeignKey(User,null=True , blank=True , on_delete=models.CASCADE) product = models.ManyToManyField(Product, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) VIEWS.py def cart_home(request): cart_obj,new_obj = Cart.objects.new_or_get(request) return render(request,"cart/cart.html",{"cart":cart_obj}) i'm tring to create user cart, cart was created but after logout and again login new cart was created, i want already exist cart and cart item -
Scraped data doesn't go to the Postgres database
The scraper should scrape every blog post on each page Data from the scraper should go to the Postgresql database, where the following statistics will be counted: The 10 most common words along with their numbers under the address /stats The 10 most common words with their numbers per author available under the address / stats / / posts authors with their name available in the address / stats / / available under the address / authors / so far I have focused on the first and second task but I have two problems (one results from the other and vice versa) I do not know how to make the data go to the database and thus I do not know how to do "Counter" Here is my scraper: import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from collections import Counter import psycopg2 # from sqlalchemy.dialects.postgresql import psycopg2 url = 'https://teonite.com/blog/page/{}/index.html' all_links = [] headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0' } with requests.Session() as s: r = s.get('https://teonite.com/blog/') soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) num_pages = int(soup.select_one('.page-number').text.split('/')[1]) for page in range(2, num_pages … -
Heroku push does not upload migrations
I have developed a Django project and want to deploy it on a Heroku server. The problem is that my migrations are not uploaded after 'heroku push' command. After I run python ./Code/manage.py makemigrations python ./Code/manage.py migrate I see my migration files and database locally. But, after that, when I push them to Heroku, they seem not to be there. My website on Heroku gives the error that some tables are not available and when I run bash on the server to see my files there aren't any migration files and the migration folders in my apps only have the init.py file. I even tried to make the migrations and migrate on the release phase. This is the Procfile: release: bash ./release_tasks.sh web: gunicorn --pythonpath Code Code.wsgi --log-file - and this is release_tasks.sh: python ./Code/manage.py makemigrations python ./Code/manage.py migrate Again, when I push to Heroku everything is ok and I see the correct migration messages, which shows that migration was successfully carried out. But still, there is no migration file on the server and my website gives the same error. -
pipenv install django without re-downloading it every time?
i have limited internet access temporarily, and every time i need to start a new django project i have to re-download django (and other dependencies) that i have already downloaded from other projects. is there an easier way to pipenv install django and other dependencies without downloading them over again every time? i read that there is a cache of these dependencies, but if thats true my issue then becomes, i dont know how to access the cache so that the dependencies install correctly into the project. or if there was one location in my 'downloads' folder where i could install directly from it, instead of from the internet. im hoping for something along the lines of: pipenv install django==2.2.0 from=c:\downloads\dependencies i expect that i will then install from previously downloaded files without the use of an internet connection. -
Why is my if statement producing a key error?
I have a view that simply checks for a key in the session store and if its present it will delete it and if its not present it should pass, it may be worth noting that the key store is holding ids of model instances. def RefreshInstances(request): if request.session['instances']: del request.session['instances'] else: pass return redirect('/') This works and achieves its goal deleting the instances, however if the key store is empty I get a key error rather than the code just being passed? Can anyone shed any light? Thanks in advance. -
How to change sender email name in Django
I need to send an email from Django with 'Team Example' as a sender and by default, no-reply@example.com is used. I have tried this as mentioned in other StackOverflow questions DEFAULT_FROM_EMAIL = 'Team Blackweb <noreply@example.com>' in settings.py but it doesn't work. -
Doing a text file items selection in Django
I have a problem of selecting multiple items on the checkbox list that I want to display on a new text file (overwriting each time). In this example, SAMPLEs, I have tried the following codes below but I still cannot find a way whereby each of the selection items in SAMPLEs (in selection_html below). Each time, when I try to select multiple items, it only gave me the latest item on the text file, named as samples.txt. Codes in views.py if request.method == 'POST' and 'btnform3' in request.POST: get_samples = request.POST.get('samples[]') f1 = open(os.path.join(settings.MEDIA_ROOT, "samples.txt"), "w+") f1.write(get_samples) Codes in selection_html (GUI where my selection items in samples will be selected by the user) <form method="post" enctype="multipart/form-data"> {% csrf_token %} <h4>SAMPLEs</h4> <input id="4" type="checkbox" name="samples[]" value="4" /> <label for="4">4</label> <br /> <input id="5" type="checkbox" name="samples[]" value="5" /> <label for="5">5</label> <br /> <input id="6" type="checkbox" name="samples[]" value="6" /> <label for="6">6</label> <br /> <p><input type = "submit" value="Submit" name="btnform3"</p> </form> Can anyone guide me and possibly provide a solution to this recurring problem of mine? Thank you. -
Celery unable to find tasks in Django app
I am pretty much following the standard project organization structure. But celery is unable to find tasks located in my apps. It can find the "debug_task" located in the celery.py but it fails to pick up tasks located in the tasks.py file of the apps. My directory structure: D:. │ manage.py │ requirements.txt │ ├───fooproject │ │ celery.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ ├───settings │ │ │ base.py │ │ │ remote.py │ │ │ __init__.py │ │ ├───bravo <- app directory │ │ admin.py │ │ apps.py │ │ models.py │ │ tasks.py <- tasks file from where it fails to pick up tasks │ │ tests.py │ │ __init__.py fooproject/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fooproject.settings') app = Celery('fooproject') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY', force=True) # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) fooproject/init.py from … -
Django - how to save form with multipule objects?
I am using Python3.7, Django 2.2. Below you can find my code, to better understand my problem. As you can see my code below, I have created table with some records. Skip polish name of the values in models.py. We have to focus only for manager_accpt. This value has 2 arguments (check file choices.py). When I create view with def manager_day_free_accpt I get multiple objects. The last column contains choice, which my user have to choose and save. Example I have put in screen below. What is my problem. I have to do it in 2 ways, beacause user will choose, which solution is more user friendly for them :) I have problem with buttons, where should i put them? Because right now, submition change whole objects, but with wrong values. When I put Buttons outside "for loop", nothing happend with objects. Can you help me, I have to find two solutions for it: 1st: Every row should contain green button with submit and reject (white button). And when user click on green button, the value only in this raw should update objects in db.. 2nd sol: User choose accept and reject in every row. After that user should push … -
Output a CSV file without downloading it
I'm doing a simple View and I want the response to be a csv file but I don't want the explorer to download it. Here I show you the response I'm giving: def csv_response(self, fields, queryset=None, filename=None): if not queryset: try: queryset = self.get_queryset() except AttributeError: raise ImproperlyConfigured('This method needs to have a queryset configured.') if not filename: filename = self.__class__ response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'inline' writer = csv.DictWriter(response, fieldnames=fields.keys(), delimiter=',') writer.writeheader() for element in queryset: writer.writerow({fieldname: getattr(element, field) for fieldname, field in fields.items()}) return response I just want it to output it in any explorer instead of downloading it, is it even possible? I think it is as I've seen some on the Internet. -
How can I rename an uploaded file on Django before sending it to amazon s3 bucket?
I have a Django App which allows a user to upload a file and save it to an s3 bucket. My question is how could I rename the file before uploading to the bucket? This is my models.py class: from converter.storage_backends import CsvStorage from django.db import models from django.utils import timezone class CSVUpload(models.Model): csv_file = models.FileField(storage=CsvStorage()) def __str__(self): return self.csv_file And this is my backend_storages.py class: from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class CsvStorage(S3Boto3Storage): location = settings.AWS_CSV_LOCATION file_overwrite = False Could anyone help me understand how to go about it? I appreciate any help you can provide -
Cannot access ListField elements from another python code
Hello I want to share a mongodb between two django apps (monitor , manager) using one application called common. I can create database instances in the manager application easily but when accessing the book authors i cannot. it return this error mongoengine.errors.FieldDoesNotExist: The fields "{'_id'}" do not exist on the document "author" models.py from mongoengine import * class author(Document): name = StringField(required = True) meta = {'abstract': True , 'allow_inheritance':True} class book(Document): name = StringField(required = True) authors = ListField(ReferenceField(author)) meta = {'abstract': True , 'allow_inheritance':True} manager.py from mongoengine import * from models import * class author(author): def rand(self): print("i am useless") class book(book): def rand2(self): print("i am also useless") if __name__ == "__main__": connect('test', host = '0.0.0.0',port = 27017) a1 = author(name = "Charef") a1.save() a2 = author(name = "hamid") a2.save() a3 = author(name = "djoudi") a3.save() a4 = author(name = "cheb khaled") a4.save() book1_authors = [a1,a2,a4] book2_authors = [a1,a3] book1 = book(name = "Hello Django", authors = book1_authors) book1.save() book2 = book(name = "Hello python", authors = book2_authors) book2.save() monitor from mongoengine import * from models import * class author(author): def say_hi(self): print("Hi, my name is {} and this is my book".format(self.name)) class book(book): def book_info(self): for author … -
How to model tournaments database into a SQL in django
I want to model a tournament database to store data of online games My question is: How to create a model in relationship database to store all this types of tournaments? (such as, league of legends tournament, dota 2 tournament) For example, a tournament can have 8 teams or 5 teams. This is the sketch I created in my mind. What things do you suggest (especially I need help with relationships of tables). Also how to keep team 1 and team 2 in the match table (such as, scores, winner, loser) i thought; Game database game_id,name Player database player_id,name,surname,country,Game(FK).. ( and some other fields) Team database team_id,name,country,game,Player(ManyToMany).. ( and some other fields) Match database match_id,name,match_game,match_map,team1,team2,winner,loser,date,duration,score1,score2.. ( and some other fields) Tournament database tournament_id,tournament_name,tournament_game,Match(ManyToMany).. ( and some other fields) -
How to keep the user logged in to a page react to the Admin page of my api django?
I have an application already running in django, I include in the header of the page a link for the user to access the django admin, how can I do to when clicking the link the admin open with the user's credentials already logged in. Is it possible to do this with react or is it better to do with django? This is the excerpt present on the react page that does the redirect <a href={${API_HOST}/admin} className="dropdown-item children-menu">Admin</a> Currently when I click on the link the redirection occurs correctly however I need to enter username and password againThis is my nav header with link to the Admin page -
django dynamic search bar without refreshing page for a particular field
I am new to django and I want to apply individual search bar for each of my model field using ajax in my centre list. It means I don't want to refresh my page and want to display the search item as I type in the search box. Please help me!! In models.py file class Centre(models.Model): name= models.CharField(max_length=50, blank=False, unique=True) address = models.CharField(max_length =250) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.") contact = models.CharField(max_length=100, blank=False) phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) # validators should be a list slug = models.SlugField(unique=False) In views.py file @method_decorator(login_required(login_url='/'), name='dispatch') class centre(CreateView): fields = ('name','address','contact','phone',) model = Centre success_url = reverse_lazy("NewApp:logindex") def form_valid(self, form): form.save() return super(centre, self).form_valid(form) @method_decorator(login_required(login_url='/'), name='dispatch') class CentreListView(ListView): context_object_name = 'centres' model = Centre @method_decorator(login_required(login_url='/'), name='dispatch') class CentreUpdateView(UpdateView): fields = ('address', 'contact', 'phone') # mention the fields to be updated while updating a school model = Centre -
Django urls page not found
In my urls.py I include my urls for each app, for example; from app.insight import urls as insight_urls urlpatterns = [ path('insight/', include(insight_urls), name='insight') ] In insight.urls I include the view and the url like this: urlpatterns = [ path('create/', InsightAddView.as_view(), name='create-insight') ] The error I get says: Page not found. No insight found matching the query However, when I change the create-insight url from create/ to create/new/ it works. Why doesn't the create/ url work? -
How to selectively process parts of a large dataset without reloading the page in Django?
I have an app which allows the user to upload a large datafile, process its contents into a python object (not Django model), and then present a summary of the contents to the user. In other words, the big data is present in the view and summarised to the template. The user then selects which of the content sections to save to the database, and submits the form to do so. I'm wrestling with how to pass the python object to the AJAX-called function without having to do all the processing again? I've used AJAX in the past and have read the answers to suggestions for not reloading pages etc, but none of them have involved passing large objects from within a view. # retrieve the file storage = TemporaryParseStorage.objects.get(id=item_id) # open the file from memory f = open(storage.file.path, "r") file_text = f.read() # Parse the file: parser = Parser() # Process its contents to create the object - I want to store this # object and call its member functions based on a button click in the template objectIWantToKeep = parser.parseModel(file_text) # Builds tree for preview tree = build_tree_from_model(storage, model) context = { 'storage': storage, 'model_name': model.name(), 'tree': tree … -
Django: Count only the latest object for each month
I am building a django based app to collect statistics about the users of a certain software. The goal is to display a chart with the number of users using a version for each month. Here is the model: class Installation(models.Model): userid = models.IntegerField() version = models.CharField(max_length=25) timestamp = models.DateTimeField(auto_now=True) where timestamp is the time when data about the user is collected. Here is how a sample table looks like: | userid | version | timestamp | |------------------------------| | 1 | 3.1 |<sometime> | |------------------------------| | 2 | 3.1 |<sometime> | |------------------------------| | 1 | 3.2 |<sometime> | |------------------------------| | 3 | 3.1 |<sometime> | <sometime> represents different timestamps from the same month. It shows that the userid = 1 upgraded to version 3.2 within the same month. Here is my approach: version_by_month = PortInstallation.objects .annotate(month=TruncMonth('timestamp')) .values('month', 'version') .annotate(Count('userid', distinct=True)) But it has a problem that it will count one user for two versions. For example, it counts userid = 1 for both versions 3.1 and 3.2 and returns the count for users using version = 3.1 as 3, which actually should be 2. For each month I am expecting to have an output in which if a user changes … -
Is there a way to create a Live Dashboard on a .Net web application using Django Python
I have not yet created but want to know if it is possible to somehow embed a dashboard that is created in Django into a .net web application. Is this to show live updates of jobs running for the user. I have not yet created No code as not created -
Django dependent form drop down
I'm creating an online bnb replica site where the user enters/registers his house/property. The idea is that the user enters the relevant data and selects his city from a drop down menu (Karachi, Quetta etc). After selecting the city, the areas of that particular city are to populate the adjacent drop down. (example: If the user selects Quetta then the areas of Quetta such as Satellite town, Model Town etc are to show) I've read through many forms,articles etc but I wasn't able to duplicate it or it's better to say understand it. So far I've just designed the models and views. Please check and give me some ideas on how to achieve it. view.py class halladd(CreateView): model = HallData template_name = "hallfiles/hall.html" form_class = HallForm def get_success_url(self): return reverse('Home-Page') models.py class City(models.Model): city_name = models.CharField("City" max_length = 150) City_CHOICES = [ (Karachi, 'Karachi'), (Lahore, 'Lahore'), (Islamabad, 'Islamabad'), (Quetta, 'Quetta'), ] hall_city = models.CharField("City", max_length = 32, choices = City_CHOICES, default = Quetta) class CityArea(models.Model): city = models.ForeignKey(City) area_name = models.CharField(max_length = 150) class HallData(models.Model): hall_name = models.CharField("Hall Name", max_length=128) hall_city = models.ForeignKey(City) hall_area = models.ForeignKey(Area) urls.py from .views import ( halladd ) urlpatterns = [ url(r'^(?i)halladd/$', halladd.as_view(), name='-View'), ] … -
[ Write API get data ]
I was assigned to write an API. The parameters of this API will be provided to partners. Our partners will submit data to this API. I was suggested by the boss to use Django to create this API. Have you guys ever done this same job? Please let me hear about ideas for making this API. Thank you for reading. I use Python. -
Page is not found while downloading the file in Django
i am working on code for pdf download that same pdf file would be downloaded every time when user click the download but when i click on download i get page not found error. as well as browser showing the path that is not the actual path of that file..my file path is /home/ujjwal/project/media. here is my settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL=' /media/' and urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html file: <a href="/media/bhagwati_invoice.pdf"> <button class="btn" style="width:100%"><i class="fa fa-download"></i> Download</button></a> and getting following error Page not found (404) Request Method: GET Request URL: http://localhost:8000/media/bhagwati_invoice.pdf