Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get latest query for user in django query
class Revision(models.Model): date_created = models.DateTimeField( db_index=True, verbose_name=_("date created"), help_text="The date and time this revision was created.", ) user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_("user"), help_text="The user who created this revision.", ) comment = models.TextField( blank=True, verbose_name=_("comment"), help_text="A text comment on this revision.", ) I need to get the latest entry for each user. But I can’t build a normal query. I am using sqlite3 database -
Deploying Django Web App using Devops CI/CD onto Azure App Service
I'm trying to deploy simple django web ap to Azure App Service using CI/CD pipeline (the most basic one that is offered by Microsoft for app deployment- no changes from me). However I'm getting the following error: 2021-03-08T16:55:51.172914117Z File "", line 219, in _call_with_frames_removed 2021-03-08T16:55:51.172918317Z File "/home/site/wwwroot/deytabank_auth/wsgi.py", line 13, in 2021-03-08T16:55:51.172923117Z from django.core.wsgi import get_wsgi_application 2021-03-08T16:55:51.172927017Z ModuleNotFoundError: No module named 'django' I checked other threads and tried doing all the things mentioned but it did not help, or I am missing something: In wsgi.py I added: import os import sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..' ) sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../licenses_api') sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../deytabank_auth') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'deytabank_auth.settings') application = get_wsgi_application() But still getting the same error, where django is not recognized. I can see that reuqirements.txt is being installed successfully and it has all the neccessary libraries there (including Django) My CI/CD yaml file looks like this: # Python to Linux Web App on Azure # Build your Python project and deploy it to Azure as a Linux Web App. # Change python version to one thats appropriate for your application. # https://docs.microsoft.com/azure/devops/pipelines/languages/python trigger: - develop variables: # Azure Resource Manager connection created during pipeline creation azureServiceConnectionId: '464b1a97-0e83-4ea3-b1cd-b8eb2bf88346' # Web app … -
django shell_plus : autoreload not working
I am using python 3.7 and have intalled IPython I am using ipython shell in django like python manage.py shell_plus and then [1]: load_ext autoreload [2]: autoreload 2 and then i am doing [1]: from boiler.tasks import add [2]: add(1,2) "testing" change add function def add(x,y): print("testing2") and then i am doing [1]: from boiler.tasks import add [2]: add(1,2) "testing" so here i found its not updating -
Unit testing log format and custom field in a Django Application
Context I created the following logger for a Django 2.2 project (python 3.6) #project/settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), 'class': 'logging.StreamHandler', 'formatter': 'verbose', 'filters': ['app_version'], }, }, 'filters': { 'app_version': { '()': 'project.utils.AppVersionFilter' }, }, 'formatters': { 'verbose': { 'format': '{"@timestamp":"%(asctime)s","@version":"%(app_version)s","level":"%(levelname)s","message":"%(message)s","logger_name":"%(module)s","thread":"%(thread)s"}', 'style': '%', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), 'propagate': True, }, }, } It works like a charm. While running runserver, I can see all my requests logged in a JSON-like syntax with the additional app_version field (using project.utils.AppVersionFilter) Problem The last assertion of this unit test fails: app_version is not defined (plus there is no sign of JSON-like syntax set by the formatter). I would like to understand why to fix it and make sure that the app's logging will remain stable. #app/tests.py class TestLoggerBehavior(TestCase): def test_log_views(self): with self.assertLogs(logger='django', level='INFO') as ctx: client = Client(HTTP_USER_AGENT='Mozilla/5.0') response = client.get('/api/etudes/non_existent_ressource/') self.assertEqual(ctx.records[0].levelname, 'WARNING') self.assertEqual(ctx.records[0].message, 'Not Found: /api/etudes/non_existent_ressource/') self.assertEqual(ctx.records[0].app_version, '1.0.0') My main guess is that I have not set logger properly in assertLogs(I found this part of the documentation a bit confusing). From the standpoint of ./app what is the logger defined in ./project/settings.py? I tried project.django, project.logging.django … -
How do you Safely Send Data From Google Script via URL Params to a Django App?
I have a script in Google that generates some data that I want to send to my web app built in Python/Django. I don't believe I can set up a CSRF token as I normally would with requests made on the webapp since I'd be sending data from the Google Environment. How is this accomplished? Currently, my url with parameters in Google Scripts looks like this: var url = 'www.mywebsite.com/door?param1=data1&param2=data2 var response = UrlFetchApp.fetch(url) Then I created url to send a data to a function in my view and I extract the params via the request. My url looks something like this: url(r'^door$', admin.door, name='door') I can easily get this to work, but I imagine this is really poor practice and leaves my site vulnerable but haven't been able to find the recommended way to solve this. Is the best way to wrap the data in a POST request? Could anyone help light the way? -
Remov bullets from Django MultipleChoiceField
Im trying to figure out how to remove bullets from Django's MultipleChoiceField. So far I have tried this very popular solution by changing my css file that basically states to input this code in my css file ul { list-style-type: none; } This didnt work and I also tried: li { list-style-type: none; } This also didnt work. Is there something Django specific why the list keeps on showing up with bulletpoints? I also tried adding the style in my forms class but also without success class SearchForm(forms.Form): job_industry = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple(attrs={'class': 'form-check', 'style': 'list-style:none;'}), choices=industry, ) I noticed that whatever attrs I enter to the forms.CheckboxSelectMultiple it only gets passed to the <label> tag and not the <ul> or <li> tag of the list. Im using Bootstrap5 if that makes any difference. How to delete bulletpoints from Django forms.MultipleChoiceField? -
How to get latest id in many to many field django
class Recept(models.Model): naslov = models.CharField(max_length=100) sestavine = models.CharField(max_length=100) priprava = models.TextField() datum = models.DateTimeField(default=timezone.now) avtor = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name="blog_recept") def last_like(self): return self.likes.latest('id') So I want to return latest id of field likes but this code returns latest id of Users how can I get the latest id of likes? -
ValueError: Missing staticfiles manifest entry on Heroku with Docker, django-pipeline, whitenoise
I am trying to deploy a Django project on Heroku using Docker, django-pipeline, and whitenoise. The container builds successfully, and I see that collectstatic generates the expected files inside container-name/static. However, upon visiting any page I receive the following 500 error: ValueError: Missing staticfiles manifest entry for 'pages/images/favicons/apple-touch-icon-57x57.png' Below are my settings.py, Dockerfile, and heroku.yml. Since I'm also using django-pipeline, one thing I'm unsure of is what setting to use for STATICFILES_STORAGE? I tried STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage' but that lead to the file paths 404ing. Any advice is appreciated. Thank you. #settings.py ... # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool("DJANGO_DEBUG", default=False) ALLOWED_HOSTS = ['.herokuapp.com', 'localhost', '127.0.0.1'] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.admindocs", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", # Third-party "allauth", "allauth.account", "debug_toolbar", "django_extensions", "pipeline", "rest_framework", "whitenoise.runserver_nostatic", "widget_tweaks", # Local ... ] MIDDLEWARE = [ "debug_toolbar.middleware.DebugToolbarMiddleware", "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ... ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = "/static/" # STATICFILES_DIRS = [str(BASE_DIR.joinpath("code/static"))] STATIC_ROOT = str(BASE_DIR.joinpath("static")) MEDIA_URL = "/media/" MEDIA_ROOT = str(BASE_DIR.joinpath("media")) # django-pipeline config STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" DEBUG_PROPAGATE_EXCEPTIONS = True STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", "pipeline.finders.PipelineFinder", ) ... # Dockerfile # Pull base image FROM python:3.8 # Set environment variables and … -
how to allow the owner of data to edit or delete in django?
I displaying the logged user expenses in my page,Now I want to let current logged user to edit their own expense.I am getting an error while doing that. I have also attached the error here. view.py def update(request,pk): expenses = expense.objects.get(id=pk) form = expenseform(instance=expenses) if request.method=="POST": form=expenseform(request.POST,instance=expenses) if form.is_valid(): form.save() return redirect('budget_home') return render(request,'budget/expenseform.html',{'Form':form}) models.py class expense(models.Model): Expensecat=(('food','Food'), ('transportation','Transportation'), ('education','Education'), ('health','Health'), ('clothes','Clothes'), ('beauty','Beauty'), ('hosuehold','Household'), ) ExpenseAmount=models.FloatField(max_length=100) Category=models.CharField(max_length=200,choices= Expensecat) Description=models.TextField(max_length=200) Date=models.DateTimeField(default=timezone.now) user=models.ForeignKey(User,on_delete=models.CASCADE) urls.py urlpatterns = [ path('',views.home,name='budget_home' ), path('chart/',views.chart,name='budget_chart'), path('income/',views.income_entry_form,name='budget_incomeform'), path('expense/',views.expense_entry_form,name='budget_expenseform'), path('update/',views.update,name='update_form'), ] Error TypeError at /update/ update() missing 1 required positional argument: 'pk' Request Method: GET Request URL: http://127.0.0.1:8000/update/ Django Version: 3.1 Exception Type: TypeError Exception Value: update() missing 1 required positional argument: 'pk' Exception Location: C:\Users\Sri Dhar\Envs\test\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response Python Executable: C:\Users\Sri Dhar\Envs\test\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\\Users\\Sri Dhar\\Dproject\\expensetracker', 'C:\\Users\\Sri Dhar\\Envs\\test\\Scripts\\python38.zip', 'c:\\python\\DLLs', 'c:\\python\\lib', 'c:\\python', 'C:\\Users\\Sri Dhar\\Envs\\test', 'C:\\Users\\Sri Dhar\\Envs\\test\\lib\\site-packages'] Server time: Mon, 08 Mar 2021 16:07:17 +0000 Traceback Switch to copy-and-paste view C:\Users\Sri Dhar\Envs\test\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\Sri Dhar\Envs\test\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars -
Get latest payment from related model in Django Admin
I'd like to draw a table using Premises model in Django Admin. In addition I'd like include the output in this table of an additional column, say "last utility payment". There may be no payment in the database so admin should able to see either an empty cell or the date of payment. I was able to write a DB query that displays the information I need. Its abbreviated and significant part is given below: SELECT jp.id, jp.number apartment, jp.building_number building, jp.rent, jp.arrears, jpm.last_payment FROM jasmin_premises jp LEFT JOIN ( SELECT pm.premises_id, max(pm.paid) last_payment FROM jasmin_payment pm GROUP BY pm.premises_id ) jpm ON jp.id = jpm.premises_id; And the output is similar to the following: id | apartment | building | rent | arrears | last_payment -------------------------------------------------------------- 170 | 1X | 6-A | 297.43 | 2.57, | NULL 72 | 2 | 4 | 289.66 | -678.38 | 2021-01-31 173 | 3Z | 7 | 432.86 | 515.72 | 2021-02-04 73 | 4 | 8-B | 292.25 | 515.44 | 2021-02-04 74 | 5 | 8-B | 112.42 | 3249.34 | NULL 75 | 6A | 122 | 328.48 | 386.23 | 2021-02-04 76 | 7 | 42 | 482.06 | … -
how can i place django rest api data into a jquery variable
I have serialized my django model data, I now want to add the data to a variable in jquery , how can i do this ? the variable in jquery named 'trackUrl' needs to read a list of the audio source urls, if you see in my API tracks page I have the data for each user, but I'm not sure in how to approach this, any ideas ? serializers.py class MusicSerializer(serializers.ModelSerializer): class Meta: model = Music fields = ['track', 'title', 'artwork', 'artist', 'date_posted'] class TrackSerializer(serializers.ModelSerializer): class Meta: model = Music fields = ['track'] views.py class TrackViewSet(viewsets.ModelViewSet): queryset = Music.objects.all() serializer_class = TrackSerializer def get_queryset(self): user = self.request.user songs = Music.objects.all().filter(artist=user) return songs Django Rest API root page Api Root The default basic root view for DefaultRouter GET /music/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "music_all": "http://127.0.0.1:8000/music/music_all/", "tracks": "http://127.0.0.1:8000/music/tracks/" } Django Rest API: tracks Track List GET /music/tracks/ HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "track": "http://127.0.0.1:8000/media/path/to/audio/1-05_Isnt_She_Lovely.mp3" }, { "track": "http://127.0.0.1:8000/media/path/to/audio/01_-_We_Will_Rock_You_1.mp3" }, { "track": "http://127.0.0.1:8000/media/path/to/audio/08_Dont_Give_Hate_A_Chance.MP3" }, { "track": "http://127.0.0.1:8000/media/path/to/audio/01_Closer.mp3" }, { "track": "http://127.0.0.1:8000/media/path/to/audio/01_Empty_Garden.mp3" } ] jquery <script> $(function() { var playerTrack = $("#player-track"), bgArtwork = $('#bg-artwork'), bgArtworkUrl, … -
Getting ProgrammingError 42000 when migrating using django
I am currently working on a project were we are using the djano-rest framework. I recently started working on the authenication and authorization, and after following the step-by-step guide https://dj-rest-auth.readthedocs.io/en/latest/installation.html and https://pypi.org/project/django-rest-authtoken/ for implementing the auth solution i get this error after calling python manage.py migrate (after makemigrations, which works fine): django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Column 'hashed_token' in table 'rest_authtoken_authtoken' is of a type that is invalid for use as a key column in an index. (1919) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Could not create constraint or index. See previous errors. (1750)"). This is the code i hav added to the models.py file: class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, date_of_birth=date_of_birth, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = … -
Trying to resolve internal server error using waitress - django - heroku
A lot of the posts regarding this issue is really old and nothing has worked for me and I'm not sure what else to do. I have a Django app that finally seems to deploy okay to Heroku. I cant use Gunicorn because I am working from a windows machine so I am using waitress. After a lot of time trying to get the correct Procfile done I finally have it where I can run on local. The problem is that when I pull up localhost on the web I get an internal server error. When I look at the trceback it gives me this: ERROR:waitress:Exception while serving / 2021-03-08T15:24:27.479552+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/waitress/channel.py", line 350, in service 2021-03-08T15:24:27.479553+00:00 app[web.1]: task.service() 2021-03-08T15:24:27.479554+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/waitress/task.py", line 171, in service 2021-03-08T15:24:27.479554+00:00 app[web.1]: self.execute() 2021-03-08T15:24:27.479555+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/waitress/task.py", line 441, in execute 2021-03-08T15:24:27.479556+00:00 app[web.1]: app_iter = self.channel.server.application(environ, start_response) 2021-03-08T15:24:27.479557+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/waitress/proxy_headers.py", line 65, in translate_proxy_headers 2021-03-08T15:24:27.479557+00:00 app[web.1]: return app(environ, start_response) 2021-03-08T15:24:27.479624+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=myapp.herokuapp.com request_id=28663c12-b4e0-41b4-b723-5193e6fbb98f fwd="208.104.195.105" dyno=web.1 connect=2ms service=9ms status=500 bytes=269 protocol=https 2021-03-08T15:24:27.479801+00:00 app[web.1]: TypeError: 'module' object is not callable I thought it might be something in my urls so I ran python manage.py check and there was a small … -
Django Advanced Python Scheduler task is running twice
I'm working on a Django project and I need it to run a function every morning at 10 AM. So I used the cron feature from Advanced Python Scheduler to do it. Here is the code that create the cron : from apscheduler.schedulers.background import BackgroundScheduler from .launcher import test def start(): print("[+] Starting task") scheduler = BackgroundScheduler() scheduler.add_job(test, 'cron', day="*",hour="18",minute="23") scheduler.start() updater.py And I used the file apps.py in order to iniate the task like so : from django.apps import AppConfig class StoreConfig(AppConfig): name = 'store' def ready(self): import store.signal from . import updater updater.start() apps.py And all of this works , the task starts but it starts two times (as you can see with the two "[+] Starting Task"): debian@lab:/var/www/$ python3 manage.py runserver 127.0.0.1:8000 [+] Starting task [+] Starting task Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 08, 2021 - 16:43:40 Django version 3.1.3, using settings 'beta.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. The strange thing is that when I do a quick modification in a file and django reload itself, it starts only one task : /store/launcher.py changed, reloading. [+] Starting task Watching for … -
Some get__absolute_url_() methods in django model
Today I faced with a problem of some get_absolute_url() methods in dj model. I was creating a todo app, For my todo I have 2 methods: set that todo is completed and delete todo, for both methods I use id of todo, then I add 2 <a/> with href for both methods: First: href="{{ task.get_absolute_url }} Second: href="{% url 'todo_completed' id=task.id %}, so this works fine, but as you can see I used 'not a good practice' at the second condition as dj says. My question is how to avoid this, maybe there is other decision for this, finally: At this app I don't want to use javascript methods like ajax, axios or fetch, thanks! I`ve the such url file urlpatterns = [ path('', todo_list, name = "todo_list_url"), path('completed/<int:id>/', todo_complete, name = 'todo_completed'), path('add/', todo_add.as_view(), name="todo_add_url"), path('delete/<int:id>/', todo_delete, name="todo_delete_url"), ] I`ve a model class TodoList(models.Model): task = models.CharField(max_length = 100, blank = False, verbose_name = "New task") completed = models.BooleanField(default = False) created_at = models.DateTimeField(auto_now_add = True, help_text = "Time when the task was created") def __str__(self): return self.task def get_absolute_url(self): return reverse('todo_delete_url', kwargs = {'id': self.id}) and my HTML file <div class="tasks"> <h2>Todoes list: ({{tasks|length}})</h2> <form class="tasks__create" action="{% url … -
How to use setup python social auth for web app and for mobile app?
We have An existing Django backend with Python social auth for signing in with Google, providing web-based application and an API for the mobile app. An iOS mobile app with GoogleSignIn pod. Now we would like to allow mobile app users to sign in with Google inside the app, and then authenticate them on the backend, so that they can access their personal data via the app. So my idea of the algorithm is: App uses the GoogleSignIn and finally receives access_token. App sends this access_token to the Backend. Backend verifies this access_token, fetches/creates the user, returns some sessionid to the App. App uses this sessionid for further requests. The problem is with the third step: token verification. I found two ways of verifying: 1. Python social auth flow As described in the docs: token = request.GET.get('access_token') user = request.backend.do_auth(token) if user: login(request, user) return 'OK' else: return 'ERROR' This would be a preferred flow, since it already have all the required steps and is working perfectly with the web app (like, accounts creation, defaults for newly created users, analytics collection, etc.). But the problem is that the backend and the app use different CLIENT_IDs for the auth. This is … -
Displaying sub-category of a category in Django
I want to list my products like this Category Sub-Category Product1 Models.py class Product(models.Model): PRODUCTS_CATEGORY = [ ('None', 'None'), ('Category1', 'Category1'), ('Category2', 'Category2'), ('Category3', 'Category3'), ('Category4', 'Category4'), ('Category5', 'Category5'), ('Category6', 'Category6') ] PRODUCTS_SUB_CATEGORY = [ ('NA', 'NA'), ('Sub-Category1', 'Sub-Category1'), ('Sub-Category2', 'Sub-Category2'), ('Sub-Category3', 'Sub-Category3'), ('Sub-Category4', 'Sub-Category4'), ('Sub-Category5', 'Sub-Category5') ] prod_id = models.AutoField prod_name = models.CharField(max_length=100) prod_category = models.CharField( max_length=100, choices=PRODUCTS_CATEGORY, default='None') prod_sub_category = models.CharField( max_length=100, choices=PRODUCTS_SUB_CATEGORY, default='NA') prod_desc = models.TextField() prod_img = models.ImageField(upload_to='product_images') slug = models.SlugField(null=True, blank=True) def __str__(self): return self.prod_name The current views.py is used to display the products in the following way Category1 Product I want additional code that gives me a different view(below) along with the above view in the same views.py function Category Sub-Category Product1 views.py def product(request): allProds = [] catprods = Product.objects.values('prod_category', 'id') cats = {item['prod_category'] for item in catprods} for cat in cats: prod = Product.objects.filter(prod_category=cat) n = len(prod) nSlides = n // 4 + ceil((n / 4) - (n // 4)) allProds.append([prod, range(1, nSlides), nSlides]) params = {'allProds': allProds, 'ster_prods': ster_prods} return render(request, 'website/products.html', params) -
Django Celery - How to make constance settings dynamic
I noticed that while using constance for settings management of my django app, celery does not seem to recognize any changes until restart. Why that? All I want is Celery to be able to read the settings live and in real-time instead of a cached vaule that just gets set during the application start-up ... I tried using constance trough redis and also trough a database table, with no noticeable change to the problem, celery will use old vaules. also see: https://github.com/jazzband/django-constance Can somebody give me a hint onto this issue? Kind regards and thanks in advance. -
How to save data total amount in model
Views def Booking(request): if request.method == 'POST': form = Bookingform(request.POST) if form.is_valid(): a = form.save() print(form.data["Number_of_Persons"]) Number_of_Persons = int(form.data["Number_of_Persons"]) Total_Amount = (Number_of_Persons * 100) print(Total_Amount) a = Booking(Number_of_Persons=Number_of_Persons, Total_Amount=Total_Amount) a.save() return HttpResponse(str(Total_Amount)) else: form = Bookingform() return render(request, 'ticketbooking.html', {'form': form}) -
Django templates: data filtering by foreign key
Im new to Django and I have a problem i can't seem to solve. Long story short, I created a text based app that helps me create a mealplan and generates a shopping list. And I'm trying to recreated with django. Here are my models: class Recipe(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=20) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name class IngredientSet(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.SET_NULL, null=True) ingredient = models.ForeignKey(Ingredient, on_delete=models.DO_NOTHING) quantity = models.FloatField() def __str__(self): return self.ingredient.name Now, on my List Views I want to display the names of stored recipes as links. Each recipe link should call a Detail View which will display selected recipe's sets of ingredients. I can't figure out how to access those by their foreign key(which points to a recipe). -
Conditional annotations with Aggregation over only some fields in Django
So lets assume i have two databases in my Django project class Article(models.Model): name = models.CharField(max_length=200) # .. class Price(models.Model): article = models.ForeignKey('Article') date = models.DateTimeField(auto_now_add=True) price = models.DecimalField() # .. There exist multiple Price entries per day for the same article. Now I want to annotate an article queryset with the average price of every article on the previous day. But I have no idea on how to do this in one efficient query. What I have done is this: articles = Articles.objects.all().select_related().filter(price__date__exact=datetime.datetime.now() - datetime.timedelta(days=1)).annotate(avg_price=Avg('price__price')) This works, if every article would have at least one price each day. But that isnt always the case. Articles that have no price for the previous day should have None or 0 or some default as avg_price. Does anybody know how to achieve this? -
Django context data is not transferred via vagrant
setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pythondb', 'USER': 'python', 'PASSWORD': 'python123', 'TEST': { 'NAME': 'test_portfolio', }, } } part1: runserver I have an application that simply extracts values from a database. part2: Vagrant However, it doesn't work via vagrant Question Why can't context_data be transferred via vagrant? -
Django - CSV Arabic language encoding
I'm working on Django Python and trying to export data in CSV format as some of the columns are in Arabic and facing issue on encoding my HttpResponse code HttpResponse(content_type='text/csv charset=utf-8') and CSV file how can I solve this Issue ? -
Passing matching value from view to html in django
So i have tried various ways from passing the value from view to html page in django. Depending upon the user logged in by matching the email I want to retrieve some information of the user in the html. In few I have faced error such as AttributeError at /user_profile'QuerySet' object has no attribute 'name' For the above method in views.py i was using # user profile def user_profile(request): user_data = UserProfile.objects.filter(emailID = request.user.email).values() context = { 'name' : user_data.name, 'emailID' : user_data.emailID, 'phone' : user_data.phone, 'college_name' : user_data.college_name, 'branch' : user_data.branch } return render(request, 'user_profile.html', context) My UserProfile model looks like this # User profile class UserProfile (models.Model): name = models.CharField(max_length=100) emailID = models.CharField(max_length=100) phone = models.CharField(max_length=15) college_name = models.CharField(max_length=200) branch = models.CharField(max_length=100) And I was using the {{context.college_name}}} in html code. If I just return the JsonResponse in the views.py I get the output properly as seen below. {"Matched data" : [{"id": 4, "name":"sample", "emailID":"lav@test.com", "phone": "1234567890", "college_name": "Dummy", "branch": "CS"}]} But while passing it to html either I am getting some error or the values are just not bein displayed. Passing the dictionary is resulting in empty dictionary being passed. # user profile def user_profile(request): user_data = … -
Track progress of individual functions running Python Django Websocket
I need to implement a live progress control using python. I have n-number of tasks being run parallel in my application, is there a way to get the Total Count of tasks being run which will help me to count the progress percentage based on Total Count. Example: 1% out of 100 2% out of 100 ' ' ' 99% out of 100 I am not understanding how to get the total_count at one place which will help me to analyse the progress of individual tasks running asynchronously.