Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Staticfiles don't load in admin on production server
As the title says, my staticfiles wont load in admin on my production server (though works fine locally). I'm using s3boto3 for staticfiles_storage. However, i've recently changed aws buckets/accounts. in my admin templates, {% url static 'static/file.js' %} still points to the old bucket/account. (e.g. https://myoldbucket.s3.amazonaws.com/admin/css/base.css?Signature=sdmlfnsdkfl%3D&Expires=1514514737&AWSAccessKeyId=AKdsfjsodifnsdiofs ) I've run collectstatic and i still have no current staticfiles. does anyone know what could be wrong? Here is my related code in settings.py: STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_ACCESS_KEY_ID = key AWS_SECRET_ACCESS_KEY = key AWS_STORAGE_BUCKET_NAME = 'mynewbucket' AWS_HEADERS = { 'Expires': 'Thu, 15 Apr 2010 20:00:00 GMT', 'Cache-Control': 'max-age=86400', } STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'staticfiles/'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static')` -
Django modal content
I have weard problem with bootstrap 4 modals and django. I need to display the modal to edit the address and return to the previous page after editing. For this purpose, i pass 2 parameters in the URL address. when both parameters are given instead of modal to edit the address, the entire page is loaded this is my view class AddresssUpdateView(generic.UpdateView): model = Address template_name = 'Order_app/address_form.html' form_class = AddressForm def get_success_url(self): return reverse_lazy('Order_app:detail', kwargs={'pk': self.object.pk}) this is my modal content (address_form.html) <div class="modal-dialog modal-lg"> <div class="modal-content"> {% if adres %} <form role="form" action="{% url 'Order_app:edit_address' pk address_id %}" method="POST"> <div class="modal-header"> <h3>Edit</h3> </div> {% endif %} <div class="modal-body"> {% csrf_token %} <div class="panel panel-default"> <div class="panel-body"> {{ form.as_p }} </div> </div> </div> <div class="modal-footer"> <div class="col-lg-12 text-right"> <input type="submit" class="btn btn-primary" name="submit" value="Save"> <button type="button" class="btn btn-default" onclick="return hide_modal()"> exit </button> </div> </div> </form> </div> this is my urls.py file url(r'^$', views.ZleceniaListView.as_view(), name='lista_zlecen'), url(r'^(?P<pk>[0-9]+)', views.OrderDetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/edit/(?P<adres_id>[0-9]+)/$', views.AddressUpdateView.as_view(), name='edit_address'), my home page template fragment <button type="button" class="btn btn-warning btn-sm" onclick="return abrir_modal('{% url 'Order_app:edit_address' order.pk address.pk %}')" data-toggle="modal" data-target="#Modal"> edit <div class="modal" id="Modal" tabindex="-1" role="dialog"></div> <script> function abrir_modal(url) { $('#Modal').load(url, function () { $(this).modal('show'); }); return false; } function … -
Getting an error 'BadRequestException' object has no attribute 'get'
I am a newbie in python and django. Trying to setup django to work with Dropbox but keep getting error "'BadRequestException' object has no attribute 'get'". Here is my code. def get_dropbox_auth_flow(web_app_session): APP_KEY= '****' APP_SECRET = '****' redirect_uri = "http://localhost:8000/dropbox" return DropboxOAuth2Flow(APP_KEY, APP_SECRET, redirect_uri, web_app_session, "dropbox-auth-csrf-token") # URL handler for /dropbox-auth-start def dropbox_auth_start(request): authorize_url = get_dropbox_auth_flow(request.session).start() return HttpResponseRedirect(authorize_url) # URL handler for /dropbox-auth-finish def dropbox_auth_finish(request): try: access_token, user_id, url_state = get_dropbox_auth_flow(request.session).finish(request.GET) # oauth_result = get_dropbox_auth_flow(request.session).finish(request.query_params) except oauth.BadRequestException as e: return e except oauth.BadStateException as e: # Start the auth flow again. return HttpResponseRedirect("http://localhost:8000/dropbox_auth_start") except oauth.CsrfException as e: return HttpResponseForbidden() except oauth.NotApprovedException as e: raise e except oauth.ProviderException as e: raise e I am following the documentation here -
Django Rest Framework Token User with MongoEngine User
i try to get token using Django Rest Framework but doesn't accept my user ValueError: Cannot assign "<User: gaurav>": "Token.user" must be a "User" instance. models class User(Document): first_name = StringField(max_length=20, required=True) last_name = StringField(max_length=20, required=True) email = StringField(max_length=20, required=True) password = StringField(max_length=200, required=True) def set_password(self,password): self.password = make_password(password) class Meta: db_table = 'User' view token = Token.objects.create(user=user) Please let me know how I can get this to work. -
Django 2.0 CreateView not working
I am very new to Django - been at it for five weeks. Not sure whether this is a bug or my own stupidity. Here is my model in an app called gcbv (for generic class-based view) from django.db import models from core.models import TimeStampModel from django.urls import reverse # Create your models here. class Vehicle(TimeStampModel): maker = models.CharField(max_length=100) model_year = models.IntegerField() vehicle_type = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) vehicle_model = models.CharField(max_length=100) website = models.URLField(max_length=100, blank=True) email = models.EmailField(max_length=100, blank=True) notes = models.TextField(blank=True, default='') def __str__(self): x = self.maker + ' ' + self.vehicle_model return x And here are the URLs from django.contrib import admin from django.urls import path, include from django.conf.urls import url from . import views from django.urls import reverse #from django.views.generic.base import TemplateView app_name = 'gcbv' urlpatterns = [ path('sub1/', views.SubView.as_view(), name='sub1'), path('vehicle_list/', views.VehicleListView.as_view(), name = 'vehicle_list'), path('vehicle/<str:slug>/', views.VehicleDetailView.as_view(), name='vehicle_detail'), path('vehicle/create', views.VehicleCreateView.as_view(), name='vehicle_create'), path('', views.IndexTemplateView.as_view(), name='index'), ] And here is the relevant view class VehicleCreateView(CreateView): model = Vehicle fields = ['maker', 'model_year', 'vehicle_type', 'slug', 'vehicle_model', 'website', 'email', 'notes'] labels = {'maker':'Maker', 'model_year':'Year', 'vehicle_type':'Type', 'vehicle_model':'Model', 'website':'Website', 'email':'Email', 'notes':'Notes'} Here is the template: {% extends "core/base.html" %} {% block body_block %} <h1>Vehicle Create for GCBV</h1> <form action="POST" action=""> {% … -
How to style a Django radio select form?
I would like to style the input button. My form already has an id on its attrs to target it on CSS. Does anyone know how I can do that? -
Django intersection of non commited model objects and commited model objects
What I have is a list of model objects I haven't run bulk_create on: objs = [Model(id=1, field=foo), Model(id=2, field=bar)] What I'd like to do is intersect objs with Model.objects.all() and return only those objects which aren't already in the database (based on the field value). For example, if my database was: [Model(id=3, field=foo)] Then the resulting objs should be: objs = [Model(id=1, field=bar)] Is something like this possible? -
Unable to add some foreign key fields
I'm getting an odd error when I run migrations that add foreign key fields ever since I upgraded to Django 2.0 django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "auth_user" Any ideas why? This is my model class: class Tag(models.Model): """ """ titles = models.ManyToManyField('main.Sentence') parent = models.ForeignKey('Tag',null=True,blank=True, on_delete=models.SET_NULL) author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) This is the migration file instantiation of it: migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('author', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)), ('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='coach.Tag')), ('titles', models.ManyToManyField(to='main.Sentence')), ], options={ 'ordering': ['-created'], }, ), And here's how the SQL is generated: ALTER TABLE "coach_tag" ADD CONSTRAINT "coach_tag_author_id_6e9296b3_fk_auth_user_id" FOREIGN KEY ("author_id") REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED; SQL Error [42830]: ERROR: there is no unique constraint matching given keys for referenced table "auth_user" org.postgresql.util.PSQLException: ERROR: there is no unique constraint matching given keys for referenced table "auth_user" I did rename some tables in my DB and had to do some modification via SQL to make things work. I'm using PostgreSQL. I renamed tables I made sure I renamed entries in django_content_type I have not renamed entries in Postgres "sequences", but the auto-inc primarykey for each table seems to still … -
django_rest_auth issue with confirmation email link
I have encountered a weird problem regarding email confirmations with the django_rest_auth app. Once I register an account I get an email with a link to account verification. However, once I click that link I get the following issue. I suspect that it is having trouble recognizing the correct url. My code in urls.py looks like this: urlpatterns = [ path('registration/account-confirm-email/<str:key>/', allauthemailconfirmation, name="account_confirm_email"), path('registration/', include('rest_auth.registration.urls')), path('facebook/', FacebookLogin.as_view(), name='fb_login'), path('twitter/', TwitterLogin.as_view(), name='twitter_login'), path('', include('rest_auth.urls')), ] The entire link to the confirmation looks something like this: http://127.0.0.1:8000/userauth/registration/account-confirm-email/NQ:1eUhNY:63MLLVxQ0bCKzspyXk4pO8VBqxA/ Thanks -
How to perform float to datetime conversion in the Django queryset
I have been searching a lot, and it's strange to me that nobody here had a similar problem. Well, in general, I need to query "available" tests which could be submitted. Let me explain this in details: I have my model (and not a permission to change it): class ScheduledTest(BaseModel): start = models.DateTimeField() duration = models.DecimalField(verbose_name="Duration (in hours)", max_digits=5, decimal_places=2) test_setup = models.ForeignKey(TestSetup, related_name="scheduled_tests") creator = models.ForeignKey(AppUser, related_name="scheduled_tests") def __str__(self): return self.test_setup.title + " | " + self.test_setup.subject.title + \ " | {}".format(self.start.date()) + " | Duration: {} h".format(self.duration) Now I want to query for ScheduledTests that have their start datetime between timezone.now() and timezone.now() + test.duration plus tests that have their start datetime bigger than timezone.now(). So this is my try: self.queryset = ScheduledTest.objects.all() available_tests = \ self.queryset.filter(start__gte=timezone.now())\ .union(self.queryset.filter(start__range=(timezone.now(), timezone.now() + timezone.timedelta(hours=F('duration')))) ) But... of course I get an exception because F('duration') cannot be calculated before the query is executed. Precisely, I get an error that hours expects float as an argument and not the F() Please help, what can I do? My idea is to somehow make a statement that will achieve conversion from float to date directly in the DB query, but I don't know how to … -
MySQL-python installation not working within virtualenv
I am trying to connect a MySQL database to my Django project, but when I try to install MySQL-python, it gives me the following error: Collecting mysql-python Using cached MySQL-python-1.2.5.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/fr/3k1nrq490dzdz9s48k49m9640000gn/T/pip-build-4dsuxwwv/mysql-python/setup.py", line 13, in <module> from setup_posix import get_config File "/private/var/folders/fr/3k1nrq490dzdz9s48k49m9640000gn/T/pip-build-4dsuxwwv/mysql-python/setup_posix.py", line 2, in <module> from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/fr/3k1nrq490dzdz9s48k49m9640000gn/T/pip-build-4dsuxwwv/mysql-python/ I have tried pip3 install ConfigParser, but while it gets installed, the error still occurs. When I try to run my Django server, it prints out a long error log, and at the end: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? and when I looked at the following link, it said that I should install MySQL-python: Django mysqlclient install May seem like a newbie question, but I can't seem to find similar errors elsewhere online. -
Change Date Time Format in Django REST Object
I've been trying to tackle this problem for quite a while now. please help if possible... I have a REST framework response where one of the datetime values is in UTC format. I want to change this format into a more readable view. rest framework output: { "data": [ { "id": "1", "start_time": "2017-12-28T12:56:55-08:00", }, { "id": "2", "start_time": "2017-12-28T12:14:10-08:00", }, { "id": "3", "start_time": "2017-12-28T09:37:35-08:00", }, ] } views: (my code to change the start_time format in the display) serializer = ChangeLogSerializer(changelog['items'], many=True) for log in serializer.data: serializer.data[log]['start_time'] = log['start_time'].strftime('%Y-%m-%d %T') Observations: serializer.data[log] doesn't appear to be correct way to update this item gives error message: File "/root/venv/dashbaord/lib/python3.4/site-packages/rest_framework/utils/encoders.py", line 68, in default return super(JSONEncoder, self).default(obj) Tried in my serializers.py file to adjust the format: start_time = serializers.DateField(format="%y-%m-%d %H:%M:%S"), but it doesn't do anything -
How to get the absolute string from a name-spaced Django URL?
You know how in a Django app, you can redirect to a different view using a simple function in your views? Its usually something like this: return redirect('myapp:my_url') The above redirect would redirect me to an absolute URL which could be something like this: https://example.com/my-url/ Now, my question is, how can I get the https://example.com/my-url/ as a string using a function in my view? I don't want to redirect, I just want to get it, and save it in my variable. So, by doing something like this: print my_function('myapp:my_url') We would get an output in the terminal like so: https://example.com/my-url/ Any help? Thanks! -
'>' not supported between instances of 'method' and 'int'
So i'm working on this matchmaking app. There's a class in my models.py that goes: class PositionMatchManager(models.Manager): def update_top_suggestions(self, user, match_int): matches = Match.objects.get_matches(user)[:match_int] for match in matches: job_set = match[0].userjob_set.all() if job_set.count > 0: for job in job_set: try: the_job = Job.objects.get(text__iexact=job.position) jobmatch, created = self.get_or_create(user=user, job=the_job) except: pass try: the_loc = Location.objects.get(name__iexact=job.location) locmatch, created = LocationMatch.objects.get_or_create(user=user, location=the_loc) except: pass try: the_employer = Employer.objects.get(name__iexact=job.employer_name) empymatch, created = EmployerMatch.objects.get_or_create(user=user, employer=the_employer) except: pass When i ran my server, i got an error message saying TypeError at /accounts/login/ '>' not supported between instances of 'method' and 'int' -
Django Model Inheritance - Query parent model for 'unkown' relationship
Take the following as an example: class Manufacturer(models.Model): name = models.CharField(max_length=200, blank=False) slug = models.SlugField(max_length=200, blank=False, unique=True) class Category(models.Model): name = models.CharField(max_length=200, blank=False) slug = models.SlugField(max_length=200, blank=False, unique=True) class Product(models.Model): category = models.ForeignKey(Category, related_name='products') manufacturer = models.ForeignKey(Manufacturer, related_name='products') name = models.CharField(max_length=50, blank=False) slug = models.SlugField(max_length=200, blank=False, unique=True) class Car(Product): pass class Food(Product): pass class CellPhone(Product): pass what I am trying to do is create a 'base' class called Product and apply a variety of 'sub-product-types' using Model Inheritance. The reason I am not using the Django's 'Abstract Model Inheritance' is because I actually want a table in my DB to hold all the products, so I can make a query like Product.objects.all() to get all the products, then type product.car to get all the field values for the related Car object. However, the problem I am running in to is that there is no way in knowing which 'relationship' a Product object has. Is it related to Car? Food? CellPhone? How should I approach this? Is there a better database schema I should be using? -
django-graphene alter column name deprecation
I would like to alter a column name in a table my database, deprecate the old field in django-graphene and add the new field. How or can I do this without creating the same column twice in my Django model? I can avoid errors during system checks while doing this, but still run into errors with my tests. Model class MyModel(BaseModel): my_column = models.CharField( max_length=255, blank=True, null=True) mycolumn = models.CharField( max_length=255, blank=True, null=True db_column='my_column') Schema class MyNode(DjangoObjectType): mycolumn = String(deprecation_reason='Deprecated') Settings SILENCED_SYSTEM_CHECKS = ['models.E007'] This works, however, now I try to run tests where I create a sample MyModel factory instance. class TestMyModel(TestModelBase): def setUp(self): self.my_model = MyModel(my_model_nm='Some model') Which, of course, throws an exception. django.db.utils.ProgrammingError: column "my_column" specified more than once I seem to be going about this wrong. How do I change a field name in django-graphene, deprecate the old name and have a new field reference the same column in my table? graphene==1.2 graphene-django==1.2.1 graphql-core==1.0.1 -
Django add hard-coded href links to an admin model's form view page
In Django's admin panel, how do I add hard-coded links to a Django model's form page (/add/ page). These are links to documentation that will never change. I want these links to appear every time on the form as a reference for the user to figure out what values to input into the fields. Do I need: Custom field? Built-in field already? Modify the admin templates somehow? Add a helper function somewhere? I'm not referring to the "change list" view; I am referring to the /change/ or /add/ page view when you go and add or edit an object within a model. models.py class DateRange(models.Model): date_name = models.CharField(max_length=100) adwords_name = models.CharField(max_length=100) bingads_name = models.CharField(max_length=100) def __str__(self): return self.date_name forms.py class DateRangeAdminForm(forms.ModelForm): class Meta: model = DateRange fields = '__all__' admin.py @admin.register(DateRange) class DateRangeAdmin(admin.ModelAdmin): form = DateRangeAdminForm list_display = ['date_name', 'adwords_name', 'bingads_name'] -
Iterable object and Django StreamingHttpResponse
I want to connect to internal http services with django and I need to buffer the output the http response of those services because some contents are very large. I am using python 3.6, django 2.0, http.client and the following code: class HTTPStreamIterAndClose(): def __init__(self, conn, res, buffsize): self.conn = conn self.res = res self.buffsize = buffsize self.length = 1 bytes_length = int(res.getheader('Content-Length')) if buffsize < bytes_length: self.length = math.ceil(bytes_length/buffsize) def __iter__(self): return self def __next__(self): buff = self.res.read(self.buffsize) if buff is b'': self.res.close() self.conn.close() raise StopIteration else: return buff def __len__(self): return self.length def passthru_http_service(request, server, timeout, path): serv = HTTPService(server, timeout) res = serv.request(path) response = StreamingHttpResponse( HTTPStreamIterAndClose(serv.connection, res, 200), content_type='application/json' ) response['Content-Length'] = res.getheader('Content-Length') return response And the reponse is empty, I test the iterator with: b''.join(HTTPStreamIterAndClose(serv.connection, res, 200) And everything works fine, I don't know why is not working. -
Unable to load model keras [Django]
I'm developing a web app where the user uploads an image and then I predict it using my model which is saved in my hard disk. I'm not sure what is causing the error. Is it image-related? I get the following error: ValueError: Fetch argument <tf.Operation 'init' type=NoOp> cannot be interpreted as a Tensor. (Operation name: "init" op: "NoOp" input: "^dense_1/kernel/Assign" input: "^dense_1/bias/Assign" input: "^dense_2/kernel/Assign" input: "^dense_2/bias/Assign" input: "^dense_3/kernel/Assign" input: "^dense_3/bias/Assign" is not an element of this graph.) My Keras config file is: { "epsilon": 1e-07, "floatx": "float32", "image_data_format": "channels_last", "backend": "tensorflow" } My python code to load model is: model = load_model('my_model.h5') model.load_weights('my_model_weights.h5') -
Return dict indexed by primary key
I have a realy simple API Endpoint which return a list of MyModel. views.py: @api_view(['GET']) def index(request): myModel = MyModel.objects.all() serializer = MyModelSerializer(myModel, many=True) return Response(serializer.data) serializers.py class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ['field1', 'field2'] Now I'd like to return a serialized dictionary of models indexed by the primary key (which is a CharField). { 'pk1':{ 'field1': 'fo', 'field2': 'bar', }, 'pk2':{ 'field1': 'fobar', 'field2': 'foo', } } -
Using Django models in different projects
Simplified project(s) structure: -DatabaseController (Project1) -App -Models -ModelActions -SomeOtherProject (Project2) -Extensions -<symlink to Project1> -App -Views -Urls Structure explanation: I have some projects, that should not directly execute Django ORM code and query the database. For that i have a separate project, called DatabaseController which does various actions like "get all subscribers" or "get subscribers count" where these actions actually execute Django ORM against a databse. So if you want to get all subscribers for SomeOtherProject (Project2) you would simply have a reference to the DatabaseController (Project1) project and call an according action. Example: In DatabaseController (Project1): class SubscriberActions: @staticmethod def get_all_subscribers(): return Subscriber.objects.all() In SomeOtherProject (Project2): from SomeOtherProject.extensions.the_symlink_to_controller.app.model_actions\ .subscriber_actions import SubscriberActions result = SubscriberActions.get_subscribers() What goes wrong: I get this error: RuntimeError: Model class SomeOtherProject.extensions.the_symlink_to_controller.app.models.partner.Partner doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. (Yes, i have to models - subscibers and partners) What am i doing wrong? How do i fix this error related to models? -
Nested Relationship Serializer Rest Framework Not Displaying Properly
I'm trying to display the attributes in the Disease Model and Evidence Model, but the attributes that is displayed on the end link are only those attributes that are present in the Rule Model. Models.py :- class Rule(models.Model): disease = models.ForeignKey(Disease, default=0,related_name="DRules") evidence = models.ForeignKey(Evidence, default=0,related_name="ERules") measure_of_belief = models.PositiveIntegerField( \ help_text="The measure of belief (percentage) that a disease is present given this evidence exists", \ default=0,validators=[MinValueValidator(0), MaxValueValidator(100)]) measure_of_disbelief = models.PositiveIntegerField( \ help_text="The measure of disbelief (percentage) that a disease is present given an evidence does not exists", \ default=0,validators=[MinValueValidator(0), MaxValueValidator(100)]) archived = models.BooleanField(default=False) def __str__(self): return "{}-{}".format(self.disease, self.evidence) class Meta: verbose_name = "Rule" verbose_name_plural = "Rules" unique_together = ('disease', 'evidence',) class Disease(models.Model): """ The model where the category will be stored """ name = models.CharField(max_length=255) advise = models.CharField(max_length=500,blank=True) archived = models.BooleanField(default=False) def __str__(self): return self.name class Meta: verbose_name = "Disease" verbose_name_plural = "Diseases" class Evidence(models.Model): evidence_choices = { ("Observable Evidence", ("Observable Evidence")), ("Cause", ("Cause")) } name = models.CharField(max_length=255) question = models.CharField(max_length=500) evidence_type = models.CharField(choices = evidence_choices,max_length=20,default="Observable Evidences") archived = models.BooleanField(default=False) image_name = models.ImageField(upload_to='media/', default='media/None/no-img.jpg') def __str__(self): return self.name class Meta: verbose_name = "Evidence" verbose_name_plural = "Evidences" Serializers.py class DiseaseSerializer(serializers.ModelSerializer): class Meta: model = Disease fields = '__all__' class EvidenceSerializer(serializers.ModelSerializer): class … -
Handling Date and DateTime timezones
I have an API which has to do with transactions. Where Parent Transaction ( PT ) can have multiple Child Transactions. Both, in Parent and Child Transaction ( CT ) i store the date-time field to UTC.( i use Django's DateTime(auto_now_add=True ) But i need to clear some things out so here are my questions: I need to import transactions from a CSV file to my current API, where most of the transactions in the CSV are in local time zone and have only date (YYYY-MM-DD) how should i handle this ? Client selects from Date picker a date ( 2017-12-28 ) how should i search that in my API? cause i don't have a time, and timezone is different. -
What's a more efficient way to create a field-less form without a dummy forms.Form?
I'm trying to implement a form that simply presents data, and offers the user the choice of "Accept" or "Deny". I'm sending the data that I want to display by overriding the get_context_data() method, and I have two <input type="submit">'s on the template. Here is the view: class FriendResponseView(LoginRequiredMixin, FormView): form_class = FriendResponseForm template_name = 'user_profile/friend_response.html' success_url = '/' def get_context_data(self, **kwargs): context = super(FriendResponseView, self).get_context_data(**kwargs) context['respond_to_user'] = self.kwargs.get('username') responding_profile = Profile.objects.get( user__username=self.request.user) requesting_profile = Profile.objects.get( user__username=self.kwargs['username']) friend_object = Friend.objects.get(requester=requesting_profile, accepter=responding_profile) context['accepter_asks'] = friend_object.requester_asks return context def form_valid(self, form): super(PairResponseView, self).form_valid(form) if 'accept' in self.request.POST: # do something else: return redirect('/') Because the form does not accept any input or choices, I have this dummy form: class FriendResponseForm(forms.Form): pass There must be a more efficient, Django way to achieve the same result. How would I go about it? -
app.yaml is not pointing to the WSGI file properly in Django with Google App Engine
I have the following files structure: And shown below, is the part of the code of my app.yaml that's pointing to the wsgi of my project: handlers: - url: /static static_dir: static/ - url: .* script: testproject.wsgi.application Of course there are other files which I think is not necessary to be shown, such as the other apps. When I ran it in local, everything is working fine. But when I upload it to the cloud, it's not working and is showing a server error. I have been researching a lot but still no luck. Please help me. Thanks!