Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - Create foreign key object on POST
I have a simple DRF REST API that I want to use to create blog articles. I want to be able to add tags to those blog articles so users can search tags and see related articles. However, the tags may not exist yet. I have created an Article Model with a ForeignKey field to a Tag Model like this: class Tag(models.Model): name = models.CharField(max_length=32) def _str__(self): return self.name class Meta: ordering = ('name',) class Article(models.Model): title = models.CharField(max_length=256) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date = models.DateTimeField(auto_now_add=True) tags = models.ForeignKey(Tag, on_delete=models.CASCADE, blank=True, default=None) def __str__(self): return self.title class Meta: ordering = ('date', 'id') Ideally what I want is to be able to POST a new Article with a set of tags, and if any of the tags don't exist, create them in the DB. However, as it is currently, the tags need to already exist to be added to the Article. Visually, DRF shows this as a dropdown that is populated with pre-existing tags: How can I make it so that I can add or create multiple tags from my Article API endpoint? -
django-widget-tweaks using field.name in render_field
I am using django-widget-tweaks and its render_field. I have an odd situation and I wonder if there is a workaround or a different approach that I should use? I am using django and allauth (I am not using the social auth part yet). I have the default django user model and I have a "Profile" model that extends the user model. That's all working. This is a specialized "Membership App". Only adults over 18 should be able to login. Once logged in a person can create "member" one or more "member" records. The logged in person is responsible for payng for memberships but might not be a member themselves; for example, a parent might log in and create member records for youth under 18 while not being a member themselves. When creating a new member record I need to give the logged in person the opportunity to create a member record for themselves (if they don't already have one). If they chose this option then the logged in person's "Profile" info should auto-fill the new member form. To facilitate this I am capturing and serializing the logged in user's Profile info and am passing it to the CBV MemberCreate method. … -
Sending .delay() and periodic_task for Celery task functions to different queues
I have a code base with several apps each with tasks.py, and have a total of 100 of these functions @periodic_task(run_every=crontab(minute='20')) def sync_calendar_availability_and_prices(listing_id_list=None, reapply_rules_after_sync=False): Its in the old format of celery periodic task definition but works fine on current celery==4.1 still These get executed every so many hours or mins via beat and also I call them ad-hoc in the codebase by using .delay(). I want all the .delay() calls to go into a certain celery queue manual_call_queue and periodic beat fired calls for same function to go to periodic_beat_fired_queue -- is this an easy 1-2 line config change somewhere at a global level to do this? I use rabbitmq, celery, django and django-celery-beat Thanks -
Trouble with chaining Q() objects with the same argument in Django's ORM
I am working on creating a cocktail recipe app as a learning exercise. I am trying to create a filter through Django's Rest Framework that accepts a string of ingredient IDs through a query parameter (?=ingredients_exclusive=1,3,4), and then searches for all recipes that have all of those ingredients. I would like to search for “All cocktails that have both rum and grenadine” and then also, separately “All cocktails that have rum, and all cocktails that have grendaine.” The three models in my app are Recipes, RecipeIngredients, and IngredientTypes. Recipes (Old Fashioned) have multiple RecipeIngredients (2oz of Whiskey), and RecipeIngredients are all of a Ingredient Type (Whiskey). I will eventually change the RecipeIngredient to a through model depending on how far I decide to take this. The list can be of a variable length, so I cannot just chain together filter functions. I have to loop through the list of ids and then build a Q(). However, I'm having some issues. Through the Django Shell, I have done this: >>> x = Recipe.objects.all() >>> q = Q(ingredients__ingredient_type=3) & Q(ingredients__ingredient_type=7) >>> x.filter(q) <QuerySet []> >>> x.filter(ingredients__ingredient_type=3).filter(ingredients__ingredient_type=7) <QuerySet [<Recipe: Rum and Tonic>]> So here's my question: Why is the Q object that ANDs … -
Batch up similar date-based queries in Django
I have a fairly complex query for finding which hotel room are available between two date ranges. It's complex because there are all sorts of conditions, it's not just cross-referencing bookings. Anyway, this is all done in-database and I get a Room QuerySet that I can .exists() on. However, one part of the system requires showing which dates in a time series (eg week, month) are available for one day and three day stays. Currently we have that running 2n queries sequentially. It's not the end of the world, but when I look in the queries pane on DDT, I feel sad inside. I would like to be able to batch this. Build a monster query off a list of datetime ranges and get an (ideally) keyed dictionary of booleans back. I'm pretty handy with the ORM but I've never seen anything like this before. And I'm straying far outside my professional experience of SQL. If I'm describing a particular type of query, please let me know. My Googles are misted up. "Sliding time range"? -
Confirming browser prefetching is causing deletes
I'm trying to test a theory that prefetching in browsers is causing unexplained deletes within my django app. Here's my delete method in my views.py: def delete(request, part_id=None): obj = epe.objects.get(id=part_id) obj.delete() logger.error('Someone deleted record: '+str(part_id)) return HttpResponseRedirect(reverse('epe_home')) And how I use the url in my template: <td><a href="{% url 'epedelete' epe.id %}"><input class="btn btn-danger" type="button" value="Delete" /></a></td> You can see I'm logging when this method is activated, but I still have had unexplained deletes without any logs from the logger. Which makes me wonder if the unexplained deletes are caused by my method at all. The only logs I have of the deletes are from MySQL logs like these: 6798 Connect user@hostname on dbname 6798 Query SET NAMES utf8 6798 Query set autocommit=0 6798 Query set autocommit=1 6798 Query SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED 6798 Query SELECT `Epe_epe`.`id`, `Epe_epe`.`epe_type`, `Epe_epe`.`epe_type2_id`, `Epe_epe`.`epe_date`, `Epe_epe`.`epe_ani`, `Epe_epe`.`epe_ani2_id`, `Epe_epe`.`epe_apn`, `Epe_epe`.`epe_apn2_id`, `Epe_epe`.`epe_weight`, `Epe_epe`.`epe_drug_type1`, `Epe_epe`.`epe_drug1`, `Epe_epe`.`epe_dose1`, `Epe_epe`.`epe_amount1`, `Epe_epe`.`epe_route1`, `Epe_epe`.`epe_time1`, `Epe_epe`.`epe_drug_type2`, `Epe_epe`.`epe_drug2`, `Epe_epe`.`epe_dose2`, `Epe_epe`.`epe_amount2`, `Epe_epe`.`epe_route2`, `Epe_epe`.`epe_time2`, `Epe_epe`.`epe_drug_type3`, `Epe_epe`.`epe_drug3`, `Epe_epe`.`epe_dose3`, `Epe_epe`.`epe_amount3`, `Epe_epe`.`epe_route3`, `Epe_epe`.`epe_time3`, `Epe_epe`.`epe_drug_type4`, `Epe_epe`.`epe_drug4`, `Epe_epe`.`epe_dose4`, `Epe_epe`.`epe_amount4`, `Epe_epe`.`epe_route4`, `Epe_epe`.`epe_time4`, `Epe_epe`.`epe_drug_type5`, `Epe_epe`.`epe_drug5`, `Epe_epe`.`epe_dose5`, `Epe_epe`.`epe_amount5`, `Epe_epe`.`epe_route5`, `Epe_epe`.`epe_time5`, `Epe_epe`.`epe_drug_type6`, `Epe_epe`.`epe_drug6`, `Epe_epe`.`epe_dose6`, `Epe_epe`.`epe_amount6`, `Epe_epe`.`epe_route6`, `Epe_epe`.`epe_time6`, `Epe_epe`.`epe_iso_start`, `Epe_epe`.`epe_iso_end`, `Epe_epe`.`epe_o2_end`, `Epe_epe`.`epe_start1`, `Epe_epe`.`epe_start2`, `Epe_epe`.`epe_start3`, `Epe_epe`.`epe_start4`, `Epe_epe`.`epe_start5`, `Epe_epe`.`epe_start6`, `Epe_epe`.`epe_start7`, `Epe_epe`.`epe_start8`, `Epe_epe`.`epe_hr1`, `Epe_epe`.`epe_hr2`, `Epe_epe`.`epe_hr3`, `Epe_epe`.`epe_hr4`, … -
zappa deploy fails with import error even though the module is present in the package
I have django project that works locally and in elasticbeanstalk. Now I'm trying to deploy it to AWS lambda using zappa. But I'm getting the following error even though the module urllib3 is present in the package zip. Any help is appreciated. Thanks. No module named urllib3: ImportError Traceback (most recent call last): File "/var/task/handler.py", line 580, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 245, in lambda_handler handler = cls() File "/var/task/handler.py", line 151, in __init__ wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS) File "/var/task/zappa/ext/django_zappa.py", line 20, in get_django_wsgi return get_wsgi_application() File "/tmp/task/django/core/wsgi.py", line 14, in get_wsgi_application django.setup() File "/tmp/task/django/__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/tmp/task/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/tmp/task/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/tmp/task/django/conf/__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/var/task/api/settings/test.py", line 4, in <module> File "/tmp/task/elasticsearch/__init__.py", line 17, in <module> from .client import Elasticsearch File "/tmp/task/elasticsearch/client/__init__.py", line 5, in <module> from ..transport import Transport File "/tmp/task/elasticsearch/transport.py", line 5, in <module> from .connection import Urllib3HttpConnection File "/tmp/task/elasticsearch/connection/__init__.py", line 3, in <module> from .http_urllib3 import Urllib3HttpConnection File "/tmp/task/elasticsearch/connection/http_urllib3.py", line 2, in <module> import urllib3 -
TypeError at /messaging/ render() takes from 3 to 4 positional arguments but 5 were given rapidsms
Top of the hour everyone Of recent, I have been following the RapidSMS web framework. Things were going fine, when I started But along the line I had to delete everything and start afresh That's when this problem started. I keep getting this error "TypeError at /messaging/ render() takes from 3 to 4 positional arguments but 5 were given rapidsms"The error screenshot -
use modelformset with queryset and extra information from your model instance
I want make a query with filter and then show it in page with the attribute that I want edit in django,how accomplish it my model: class DailyReport(models.Model): userInfo = models.ForeignKey(UserInfo, on_delete=models.CASCADE) enterTime = models.DateTimeField(null=True, blank=True) exitTime = models.DateTimeField(null=True, blank=True) # add null=True in production mode overTimeWork = models.FloatField(default=0) absenceTime = models.FloatField(default=0) restTime = models.FloatField(default=0) archive = models.BooleanField(default=False) rest = models.BooleanField(default=False) absence = models.BooleanField(default=False) class UserInfo(models.Model): name = models.CharField(max_length=200, verbose_name='نام') family = models.CharField(max_length=200, verbose_name="نام خانوادگی") job = models.CharField(max_length=400, verbose_name="شغل") startWorkTime = models.TimeField(verbose_name="ساعت شروع") finishWorkTime = models.TimeField(verbose_name="ساعت اتمام") allowedWorkTime = models.IntegerField(verbose_name=" ساعت کار") allowedabsenceTime = models.FloatField() allowedOverTimeWork = models.FloatField() # better define custom field for getting hour fixedSalary = models.FloatField(verbose_name="حقوق ثابت") # define custom Field for Salary overTimeHourSalary = models.FloatField( verbose_name="حقوق ساعت اضافه کار") # define Field as above for Enter hour salary absenceTimeHourSurcharge = models.FloatField(verbose_name="جریمه ساعت غیبت") restTimeHourSubtraction = models.FloatField(verbose_name=" کسر ساعت مرخصی") my modelform: class DailyAbsenceRestForm(forms.ModelForm): class Meta: model = DailyReport fields = ['absence', 'rest'] my modelformset: my_formset = modelformset_factory(DailyReport, form=DailyAbsenceRestForm) formset=my_formset(queryset=DailyReport.objects.filter(exitTime__day=13).filter(userInfo__name='hassan')) but when I print formset in django template it only show me rest and absence field but I want show me info about DailyReport name and family enterTime exitTime and .... how accomplish it in django? -
Optimizing DRF post request handling by preventing full response serialization back
It appears when POSTing to a DRF endpoint, when using the out of the box ViewSets, responds back with the entire data serialized back. When posting several thousand objects (which also have related fileds), the serialization is heavy as well as unnecessary. I already know what I posted, and I don't even need the pks back so I would like to prevent that serialization response from happening, and instead will settle for number of rows inserted or something. I found a resource about optimizing DB queries for related fields when serializing, but couldn't find any resource about a way to easily prevent that entire serialization from happening. Additionally, I'd like to get comments for the practice of preventing the full serialization of objects created with a POST. -
Model & History Model (Same fields), Copy data from one to another
I have a two models, A and HistoryA class A(models.Model): title = .... slug = .... done = .... date_done = .... class HistoryA(models.Model): parent = ForeignKey(A) title = .... slug = .... done = .... date_done = .... When a user after creating a A instance, try to edit it; a new instance of HistoryA is created saving all the old data. But if that user decides to discard the changes, the old data that were in HistoryA must move back to A How I can copy all the value from HistoryA to A, without typing all the fields one by one, like: # Just an example A_instance.attributes = HistotyA_instance.attributes A_instance.save() Basically it's just a way to create History for a model. -
Can't log in with Django REST Framework custom User extending AbstractBaseUser
Using Django REST Framework, I've created a custom user that authenticates using a phone number instead of username. I can successfully create a superuser using create_superuser and the superuser does appear in the database. However, when I enter the login page, I can't login with the phone number and password I've chosen (yes, I've double and triple checked the password/phone number and tried multiple different passwords/phone numbers). Here is (a stub of) my custom user class' models.py file: class User(AbstractBaseUser, PermissionsMixin): phone_regex = RegexValidator( regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(_('phone number'), unique=True, validators=[phone_regex], max_length=17, blank=True) . . . objects = UserManager() USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = ['first_name', 'last_name'] serializers.py: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'phone_number', 'groups') managers.py: class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, phone_number, password, **extra_fields): """ Creates and saves a User with the given phone number and password. """ if not phone_number: raise ValueError('The phone number must be set') user = self.model(phone_number=phone_number, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, phone_number, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(phone_number, password, **extra_fields) def create_superuser(self, phone_number, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise … -
Slugify a thread link and create it on the home.html
I am trying to slugify my hyperlinks. I created a Django board (home.html): {% for topic in topics %} <tr> <td>{{ topic.slug }}</td> <td><a href="{% url 'topic_posts' topic.pk %}">{{ topic.subject }}</a></td> <td>{{ topic.starter.username }}</td> <td>0</td> <td>0</td> <td>{{ topic.last_updated }}</td> </tr> {% endfor %} You can see, the slugs were created. (First column = {{ topic.slug }}) How can I link them to my thread hyperlinks? (e. g. "hallo das ist ein test :9") My current code in views.py: def home(request): topics = Topic.objects.all() return render(request, 'home.html', {'topics': topics}) def topic_posts(request, topic_pk): topic = get_object_or_404(Topic, pk=topic_pk) return render(request, 'topic_posts.html', {'topic': topic}) My current url.py: urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^admin/', admin.site.urls), url(r'^new/$', views.new_topic, name='new_topic'), url(r'^request/(?P<topic_pk>\d+)/$', views.topic_posts, name='topic_posts'), url(r'^request/(?P<topic_pk>\d+)/reply/$', views.reply_topic, name='reply_topic'), ] I already tried different approaches like: def home(request): topics = Topic.objects.all() slug = Topic.slug return render(request, 'home.html', {'topics': topics, 'slug': slug}) def topic_posts(request, slug): slug = get_object_or_404(Topic, pk=slug) return render(request, 'topic_posts.html', {'slug': slug}) home.html: <td><a href="{% url 'topic_posts' topic.slug %}">{{ topic.subject }}</a></td> url.py: urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^admin/', admin.site.urls), url(r'^new/$', views.new_topic, name='new_topic'), url(r'^request/(?P<slug>[-\w\d]+)/$', views.topic_posts, name='topic_posts'), url(r'^request/(?P<topic_pk>\d+)/reply/$', views.reply_topic, name='reply_topic'), ] What I am doing wrong here...? -
How to validate CHOICES for objects.create() method?
I have the following model: from django.db import models class Artist(models.Model): TYPE_CHOICES = ( ('Person', 'Person'), ('Group', 'Group'), ('Other', 'Other'),) name = models.CharField(max_length=100) type = models.CharField(max_length=20, choices=TYPE_CHOICES) The problem is that if I create an object like this: Artist.objects.create(...) the type validation doesn't work. How can I activate the validation for this? -
Django Automated Testing doesn't work with heroku postgresql database
I made a Django app from the tutorial using a postgresql database. The automated testing worked fine when my app was running locally. I have since deployed it to heroku and when I try to run the tests I get this error: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the default database instead. RuntimeWarning Got an error creating the test database: permission denied to create database I've searched far and wide and haven't found a solution to this. My app otherwise works fine. It has no issues reading from the database. It just won't run my tests. The only way I've found to make my tests work is to manually copy and paste the database credentials for my local database into settings.py and then change them back after my tests are run but thats a silly solution to this. How do I fix this? -
django 500 error coming instead of 404 for custom error page
here is my views.py def handler_404(request): return render(request, '404.html', status=404) def handler_500(request): return render(request, '500.html', status=404) here is my urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from finish.views import handler_404,handler_500 from django.conf.urls import ( handler400, handler403, handler404, handler500 ) urlpatterns = [ path('', include("scrap.urls")), path('', include("details.urls")), path('', include("finalize.urls")), path('', include("finish.urls")), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) handler404 = handler_404 handler500 = handler_500 when i am typing some url in which is not exist it is coming "Server Error(500)" instead of coming "page not found(404)" error. Please have a look into this.... -
Web Framework recommended for Web application
In my job, I have thought about developing a web application to obtain information from 3 databases. SQL SERVER ORACLE REDSHIFT(Postgre SQL) Each one has some tables and a model, and in the 3 databases some tables are related in some way (By Ids, or dates, amounts ..) My idea is to develop a web application that shows graphs of amounts for example comparing with the tables of those systems. And in the case that there is a difference, show the user a notification when you login in the application. I have some experience in PHP, BOOTSTRAP, JQUERY, JAVASCRIPT. I have thought to use DJANGO for the functionalities that it has and since it is the framework that I have access from PyCharm in the machines. Is it recommended to use DJANGO for this project? -
Django redirects to login page even after logging in (I have used custom login login form)
code in views.py: from django.contrib.auth import authenticate, login as auth_login def login_view(request): if request.method=="POST": login_form = LoginForm(request.POST) if login_form.is_valid(): data = login_form.cleaned_data password = data["password"] username = data["username"] user = authenticate(username=username, password=password) if user is not None: auth_login(request, user) return redirect(reverse("account:profile", args=(user.id,))) else: validation_error = "Enter a valid email or password" return render(request, "account/login.html", {"form": login_form, "error": validation_error}) else: login_form = LoginForm() return render(request, "account/login.html", {"form": login_form, "error": ""}) On going to "/" I'm redirected to "/accounts/login" which take me to the login page. After I enter the username and password, it takes me to the user profile page. So far so good. Now Instead of being redirected to "/", I'm being redirected to "/accounts/login" again and am being shown the login page again. Why? -
How to fix warnings after upgrading from Django 1.7 to 1.8?
Getting the warning: models.py:15: RemovedInDjango19Warning: Model class myapp.MyModel doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded. This will no longer be supported in Django 1.9. I replaced: from .models import MyModel To from myapp.models import MyModel Also, I am using 'myapp.models' at ForeignKey fields -
Changing a project name in django
I changed the name of my django project from oldname to newname using Pycharm's refactor > rename. I have scoured through the project and it seems to have changed the name everywhere. But when I try runserver, here's what I get, Traceback (most recent call last): File "/Users/melissa/Dropbox/newname/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/melissa/Dropbox/newname/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/melissa/Dropbox/newname/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/Users/melissa/Dropbox/newname/env/lib/python3.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/melissa/Dropbox/newname/env/lib/python3.7/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Users/melissa/Dropbox/newname/env/lib/python3.7/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python/3.7.0/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 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 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 'oldname' Can someone help me with this? -
Custom User Model Django TypeError: create_user() missing 1 required positional argument: 'username'
I am creating a custom User model and I am getting an error when I create my super user for the first time . Any advice please . I would ideally like to user BOTH my username or email for verification interchangeably , but this may be a question for another day. I started initially with email as my username_field but changed after a while. Please can someone provide guidance please. I have posted my models.py file which sits inside the accounts app. from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) class UserManager(BaseUserManager): def create_user(self, email, username, password=None, is_active=True, is_staff=False, is_admin=False, is_client=True, # anyone registered can be a client is_partner=False ): if not username: raise ValueError("Unique username is required") if not email: raise ValueError("User must have an email address") if not password: raise ValueError("Password is required") user_obj = self.model( email=self.normalize_username(username) ) user_obj.set_password(password) # change user password user_obj.username = username user_obj.email = email user_obj.staff = is_staff user_obj.client = is_client user_obj.partner = is_partner user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staff_user(self, username, password=None): user = self.create_user( username, password=password, is_staff=True ) return user def create_partner_user(self, username, password=None): user = self.create_user( username, password=password, is_partner=True ) return user def … -
Unable to Render Form in Django
I'm trying to import a simple single-field form in Django, and I have gone through plenty of Tutorial Videos on YouTube describing the same. Yet, I'm unable to render the simple form on my web-app. I'm pretty sure I'm doing something really stupid that is still oblivious to me. I'll also post in the Folder structure so you can suggest if I'm defining the class/function in the wrong views.py file. To keep things short I'll quickly post the appropriate source codes as follows: earthquake/views.py File from django.shortcuts import render from earthquake.forms import HomeForm from django.views.generic import TemplateView class HomeView(TemplateView): template_name = 'earthquake/home.html' def get(self, request, *args, **kwargs): form1 = HomeForm() argf = { 'myform': form1 } return render(request, self.template_name, argf) forms.py from django import forms class HomeForm(forms.Form): post = forms.CharField() home.html (snippet) <div class="container"> <div class="jumbotron"> <h1>Query Form</h1> <p>Please Enter the parameters you want to query against the USGS Earthquake DB</p> <div class="container"> <form class="" method="post" action=""> {% csrf_token %} {{ myform }} <button type="submit" class="btn btn-success">Search</button> </form> </div> </div> </div> Folder Structure https://i.stack.imgur.com/zoehT.jpg (In case you're unable to see the last entry in the image, it's the main views.py present in the project folder) The following is the snapshot … -
How do I use a template for a login in django?
[enter image description here][1] Hello! I'm doing a job at the university but I can not use an html template with css because the html of my login is different to everything I know. this is my html base https://i.stack.imgur.com/pkoZS.png and this is the form https://i.stack.imgur.com/GJhhs.png these two things return this to me in the browser https://imgur.com/b0V6omw but I need you to visualize in this way with a html and css of all the life https://i.stack.imgur.com/pkoZS.png I would really appreciate the help. -
Django: form works in index but not in a particular page
I'm having multiple forms around my website. However, a have a particular form that is working in the home page (index.html), but when coping this particular form in a section of my site it doesn't work anymore (on this section, if I return to home everything works as expected). What am I missing? Views.py: from django.shortcuts import render, HttpResponse, HttpResponseRedirect from .models import Treasure, TamaniosCantidades from .forms import TreasureForm, TamaniosCantidadesForm, LoginForm from django.contrib.auth import authenticate, login, logout # Create your views here. def index(request): treasures = Treasure.objects.all() form = TreasureForm() tamanioscantidades_form = TamaniosCantidadesForm() return render(request, 'main_app/index.html', {'treasures': treasures, 'form': form, 'tamanioscantidades_form': tamanioscantidades_form}) def productos(request): treasures = Treasure.objects.all() form = TreasureForm() return render(request, 'main_app/productos.html', {'treasures': treasures, 'form': form}) def die_cut(request): tamanioscantidades_form = TamaniosCantidadesForm() return render(request, 'main_app/die-cut-stickers.html', {'tamanioscantidades_form': tamanioscantidades_form}) def post_tamanioscantidades(request): form = TamaniosCantidadesForm(request.POST) if form.is_valid(): tamanioscantidades = TamaniosCantidades(tamanios=form.cleaned_data['tamanios'], cantidades=form.cleaned_data['cantidades']) # tamanioscantidades = tamanioscantidades_form.save(commit = False) # tamanioscantidades.usuario = request.user tamanioscantidades.save() return HttpResponseRedirect('/') def post_treasure(request): form = TreasureForm(request.POST) if form.is_valid(): treasure = Treasure(name=form.cleaned_data['name'], value=form.cleaned_data['value']) treasure.save() return HttpResponseRedirect('/') urls.py: app_name = 'main_app' urlpatterns = [ path('', views.index), path('productos/', views.productos), path('productos/die-cut-stickers', views.die_cut, name='die-cut-stickers'), path('post_url/', views.post_treasure, name='post_treasure'), path('post_url_tamanioscantidades/', views.post_tamanioscantidades, name='post_tamanioscantidades'), ] *html**: <div class="col-md-6 border border-primary rounded border-3"> <div class="m-5"> <div class="row"> <form action="post_url_tamanioscantidades/" method="post"> … -
Simple Math on Django Views with Decimals
I'm in a little gambit with this question here "conversion from method to Decimal is not supported django" error where adding the () gives me an error 'DeferredAttribute' object is not callable and removing them gives me another conversion from DeferredAttribute to Decimal is not supported (My current error with the code below) My goal is two take my 3 values and figure out what the profit or loss is: Profit_long = (price 1 - price 2) * size *I'm not entriely sure if the math syntax is right yet because the above error message won't let me get that far. From what I've read as long as those variables are integers the math syntax should be right. Not sure if it will work with decimals. That's step two. First I need to solve the above issue. views.py class TradeDetailView(DetailView): template_name = 'tj/cp/trade/detail.html' queryset = Trade.objects.all() def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(Trade, id=id_) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) entry_price = Decimal(Trade.entry_price) exit_price = Decimal(Trade.entry_price) size = Decimal(Trade.size) context['profit_long'] = (entry_price - exit_price) * size return context models.py class Trade(models.Model): ... size = models.DecimalField(null=True, blank=True, max_digits=50, decimal_places=2) entry_price = models.DecimalField(null=True, blank=True, max_digits=50, decimal_places=2) exit_price = models.DecimalField(null=True, blank=True, max_digits=50, decimal_places=2) …