Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django assertRedirects test fails due to http://testserver prefix
I want to test that /sitemap.xml/ redirects to /sitemap.xml. I'm using this code: res = self.client.get('/sitemap.xml/') self.assertRedirects(res, '/sitemap.xml', status_code=301) And getting the following error: AssertionError: Response redirected to 'http://testserver/sitemap.xml', expected '/sitemap.xml' How should I write this test to avoid the testserver clash? -
Keep getting error when i try to runserver in Django
I keep getting this error when I try runserver (mysite) Brians-MBP:mysite brian-admin$ python manage.py runserver Performing system checks... Unhandled exception in thread started by .wrapper at 0x10a8d4d90> Traceback (most recent call last): File "/Users/brian-admin/anaconda3/envs/mysite/lib/python3.6/site-packages/django/urls/resolvers.py", line 542, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/brian-admin/anaconda3/envs/mysite/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/brian-admin/anaconda3/envs/mysite/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/Users/brian-admin/anaconda3/envs/mysite/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/brian-admin/anaconda3/envs/mysite/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/brian-admin/anaconda3/envs/mysite/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/brian-admin/anaconda3/envs/mysite/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/brian-admin/anaconda3/envs/mysite/lib/python3.6/site-packages/django/core/checks/urls.py", line 67, in _load_all_namespaces namespaces.extend(_load_all_namespaces(pattern, current)) File "/Users/brian-admin/anaconda3/envs/mysite/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Users/brian-admin/anaconda3/envs/mysite/lib/python3.6/site-packages/django/utils/functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "/Users/brian-admin/anaconda3/envs/mysite/lib/python3.6/site-packages/django/urls/resolvers.py", line 549, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Everything should be fine, I don't know why I keep getting this error. -
proxybroker RuntimeError: There is no current event loop in thread 'Dummy-1'
I am using Proxybroker and django, when i run proxybroker with command line or single python script, it works fine, i followed the example code on proxybroker, but when i use django it shows errors.: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x108b17d90> Traceback (most recent call last): File "/Users/sun/Documents/pycharm_project/AlliedRateChangeWebBackend/AlliedRateChangeWebBackend/orbitz/urls.py", line 2, in <module> from .views import GetRateView,GetDefaultPriceView,PostDataView,PostRezPower,AccountInfo,LoginAccount,LoginSetting,ConnectRezlight File "/Users/sun/Documents/pycharm_project/AlliedRateChangeWebBackend/AlliedRateChangeWebBackend/orbitz/views.py", line 16, in <module> from .getProxies import runFetch File "/Users/sun/Documents/pycharm_project/AlliedRateChangeWebBackend/AlliedRateChangeWebBackend/orbitz/getProxies.py", line 2, in <module> from proxybroker import Broker File "/Users/sun/anaconda/envs/ratechange/lib/python3.6/site-packages/proxybroker/__init__.py", line 29, in <module> from .judge import Judge # noqa File "/Users/sun/anaconda/envs/ratechange/lib/python3.6/site-packages/proxybroker/judge.py", line 14, in <module> class Judge: File "/Users/sun/anaconda/envs/ratechange/lib/python3.6/site-packages/proxybroker/judge.py", line 18, in Judge ev = {'HTTP': asyncio.Event(), 'HTTPS': asyncio.Event(), File "/Users/sun/anaconda/envs/ratechange/lib/python3.6/asyncio/locks.py", line 226, in __init__ self._loop = events.get_event_loop() File "/Users/sun/anaconda/envs/ratechange/lib/python3.6/asyncio/events.py", line 678, in get_event_loop return get_event_loop_policy().get_event_loop() File "/Users/sun/anaconda/envs/ratechange/lib/python3.6/asyncio/events.py", line 584, in get_event_loop % threading.current_thread().name) RuntimeError: There is no current event loop in thread 'Dummy-1'. Please help, thanks -
May a specific internet network service be prgrammed to be spied??? By unknown users .
How can I physically or programmably determine if my internet network service mobile cams are spied ? Is there any practical way to check this you may suggest... lost 4 hard discs full of 1TB data plus 2 modems plus 4 mobile phones plus a year 24 months in this issue ONLY Proffessional answers in"ENGLISH"" please in order not to mix up. Winning answer will be prized. -
Django: Link data to ManyToManyField
For example, in Django, you create models called "Skill" and "Person" and associate them with models.ManyToManyField from Person side. Skill has a score attribute, the higher the score of that skill, the higher the skill. Then, in the Project attribute on the Person side, items like "Skill A: 87", "Skill B: 45", "Skill C: 62", "Skill D: 100" ,,,, are lined up. Ideally, you want to enter numerical values for each item side by side like "Skill A", "Skill B", "Skill C", "Skill D" ,,,. How can I do this? It seems that it is hard to find out how to combine an associative array and models.ManyToManyField. -
Stats by month in template
I'm trying to create a simple dashboard that will indicate the number of orders by month. Each order has an invoice date, which is in the form of YYYY-MM-DD models.py class Order(models.Model): user = models.ForeignKey(UserCheckout, null=True, on_delete=models.CASCADE) invoice_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) def total(self): qs = Order.objects.filter(invoice_date[0:6]=self) qs.count() return qs template.html {% for month in monthyear %} {{month}}: {{month.total}} {% endfor %} monthyear will need to be a queryset of months/year in the form of 2018-07 (i.e. July of 2018) 1) How would I get a queryset of monthyear rather than writing out a huge list of year-month strings for the next 50 or 60 months? 2) Is my query set in the total function correct from a syntax point of view? 3) Am I calling the function correctly within the template? 4) Is there an easier way to do this? Thanks! -
bokeh model does not exist
I have django bokeh project and I'm trying to add dateRangePicker slider but I get error in console bokeh-0.12.16.min.js:1 Uncaught Error: Model 'DateRangeSlider' does not exist. This could be due to a widget or a custom model not being registered before first usage. This is code for that. date_range_slider = DateRangeSlider(title="Date Range: ", start='2018-01-02', end='2018-06-09', value=('2018-06-02', '2018-06-09'), step=1) # l = layout(children=[[date_range_slider]], sizing_mode='fixed') l = layout(children=[[p], [date_range_slider]], sizing_mode='fixed') script, div = components(l) print(div) return render(request, 'index.html', {"the_script": script, "the_div": div}) Do I need to add anything in django model? -
django ckeditor ckwebspeech
has anyone successfully integrated ckeditor plugin ckwebspeech with Django for speech to text? I have downloaded the plugin into my ckeditor/plugins directory and added the following CKEDITOR_CONFIGS to Django settings.py but the plugin is not available in my toolbar: CKEDITOR_CONFIGS = { "default": { 'toolbar_CustomToolbarConfig': [ ['Styles', 'Format', 'Font', 'FontSize'], ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', 'RemoveFormat', 'Scayt'], ['TextColor', 'BGColor'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'], ['Image', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar'], ['Find', 'Replace', 'SelectAll', 'Selection'], ['Link', 'Unlink','ckwebspeech'] ], 'disableNativeSpellChecker': False, "removePlugins": 'elementspath,stylesheetparser,contextmenu', 'toolbar': 'CustomToolbarConfig', 'extraPlugins': ','.join(['wsc','ckwebspeech']), 'entities': False, }, } Is anyone able to provide some guidance on how I can get this plugin to be available in the toolbar? Any help is much appreciated! -
Django: formset not saving
I have a formset that I can render to a template and when it is submitted it get's updated in the database. However, the page just refreshes and I can't seem to get it to go to another page. I save the formset in my formset.is_valid() section which is inside my get_context_data. I created a def get_success_url(self):, but this is not happening even though it is successfull. I'm using {% for erro in form.errors %} in my html page that tells me I'm not getting errors. Plus it is saving to the database! But the question remains: How do I get this to revert to a new page after I hit submit? html <form method="post">{% csrf_token %} ... <button type="submit" class="btn btn-primary">Submit</button> </form> view class LibraryUpdateView(LoginRequiredMixin, UpdateView): model = Book form_class = BookForm template_name = 'library/library_update.html' def get_context_data(self, *args, **kwargs): context = super(LibraryUpdateView, self).get_context_data(*args, **kwargs) print(self.object) print('hi') qs = Library.objects.filter( library_id = self.kwargs.get('library_id') ) if self.request.POST: context['getperinfo_form'] = BookFormSet(self.request.POST,instance=qs.first()) formset = BookFormSet(self.request.POST,instance=qs.first()) ######## THIS DOES HAPPEN ############# if formset.is_valid(): print('we valid?') formset.save() else: print('we not valid') messages.api.add_message(self.request, messages.ERROR, "Something is wrong!!!") else: qs = Library.objects.filter( library_id = self.kwargs.get('library_id') ) context['getperinfo_form'] = BookInfoFormSet(instance=qs.first()) context['hi']=3 return context def form_valid(self, form): ### THIS … -
ModelForm: search for existing entry in Model vs forms.Form: save entry
I am attempting to create a website in which, once a user enters a 'search query', it loads a page with all 'locations' associated with that 'search_query' in the database (ultimately, those 'locations' will be got from Twitter API, but that's for another day :P). To summarise the issue: Once a user enters text into the form, there are two options: The text represents an existing search_text in the database, or The text does not represent an existing search_text in the database. OPTION 1: The text represents an existing search_text in the database In this circumstance, I wish to: Render an HTML page with the search_text entered and the locations associated with that search_text. OPTION 2: The text does not represent an existing search_text in the database In this circumstance, I wish to: Save the text entered as a search_text to the Hashtag model. Render an HTML page with the search_text entered and the locations associated with that search_text*. EXAMPLE For example, assuming the user enters "monty" in the Form: Check whether "monty" is an existing search_text in the Hashtag model, If yes, render a HTML page with the locations associated with "monty" in the Hashtag model. If no, save … -
Celery/SQS task retry gone haywire - how to get rid of it?
We've got Celery/SQS set up for asynchronous task management. We're running Django for our framework. We have a celery task that has a self.retry() in it. Max_retries is set to 15. The retry is happening with an exponential backoff and takes 182 hours to complete all 15 retries. Last week, this task went haywire, I think due to a bug in our code not properly handling a service outage. It resulted in exponential creation (retrying?) of the same celery task. It eventually used up all available memory and the worker crashed. Restarting the worker results in another crash a couple hours later, since all those tasks (and their retries) keep retrying and spawning new retries until we run out of memory again. Ultimately we ended up with nearly 600k tasks created! We need our workers to ignore all the tasks with a specific celery GUID. Ideally we could just get rid of them for good. I was going to use revoke() but, per documentation (http://docs.celeryproject.org/en/3.1/userguide/workers.html#commands), this is only implemented for Redis and RabbitMQ, not SQS. Furthermore, when I go to the SQS service in the AWS console, it's showing zero messages in flight so it's not like I can just … -
add to cart using django rest framework
I am thinking of creating a production ready e-commerce application. However I am stuck in add to cart functionality. For adding the product to the cart, the things required are product object and quantity, i think. I have created the serializer CartSerializer and CartItemSerializer and also the APIView part but I am confused which serializer to use or I have to make a different serializer which will have only field of product object and quantity to post. Because with my code, I am getting all the fields. Here is my code class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE) items = models.ManyToManyField(Cycle, through='CartItem') updated = models.DateTimeField(auto_now_add=False, auto_now=True) subtotal = models.DecimalField(max_digits=50, decimal_places=2, default=0.00) tax_percentage = models.DecimalField(max_digits=10, decimal_places=5, default=0.085) tax_total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00) total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00) active = models.BooleanField(default=True) objects = CartManager() def __str__(self): return str(self.id) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) item = models.ForeignKey(Cycle, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) line_item_total = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.cart.id serializers.py class CartSerializer(serializers.ModelSerializer): product = serializers.SerializerMethodField() class Meta: model = Cart fields = '__all__' @staticmethod def get_product(obj): return obj.product.name class CartItemSerializer(serializers.ModelSerializer): item = serializers.SerializerMethodField() item_title = serializers.SerializerMethodField() product = serializers.SerializerMethodField() price = serializers.SerializerMethodField() class Meta: model = CartItem fields = [ "item", … -
How to change date_joined & datetimefield format in Django?
I use basic User model for date_joined field. And I already did almost of ways in google search. serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'is_superuser', 'is_staff', 'is_active', 'date_joined', 'get_absolute_url') settings.py USE_L10N = False USE_TZ = False DATETIME_FORMAT = '%d-%m-%Y-%H-%M-%S' template.html <td>{{ user.date_joined }}</td> <td>{{ user.date_joined|date:"d:m:Y H:i:s" }}</td> And I got results like this {{ user.date_joined }} => 2018-06-14T12:02:21 {{ user.date_joined|date:"d:m:Y H:i:s" }} => (nothing) {{ user.date_joined|date:"DATETIME_FORMAT" }} => (nothing) {{ user.date_joined|date:DATETIME_FORMAT }} => (error) I also use user solution to other my models. models.py class TimeStampedModel(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) -
possible to get attributes of a model as values or values_list? django
I know that with queryset we can use.values() or values_list() to get the fields / attributes we want But what if we already have the class 'app.models.Sample' for example I know we can do something like a = A.objects.filter(id=1).values('name') but what if I have something like b = B.objects.filter(id=2).first() b.name = 'changes' b.field = 'another field' b.save() return b.values('name') # I know this does not work but is there something like this? Just being curious and tried to google around but not sure if there's a wording for this so couldn't get much. -
AJAX POST request to Python method - Post hits right file location, but shows 404
I've been looking at how to integrate AJAX calls into a Python Django application and I'm somewhat new to both. I have been following the advice here: https://www.quora.com/Can-I-execute-a-Python-function-from-JavaScript Which led to this and this respectively for AJAX and Django advice.Both made pretty good sense to me. The desired end result is that a template in this fourth folder down (dashboard) call a function in a file called logic.py under the api folder above it: In a JavaScript file hooked up to my django template, I have the following code I stole from the AJAX resource I listed above and made some light edits to: window.onerror = function() { debugger; } // browser - safety var request; if (window.XMLHttpRequest) { request = new XMLHttpRequest(); } else if(window.ActiveXObject) { // ie try { request = new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) { try { request = new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} } } function step2() { console.log('something'); } function testLogin() { request.open('POST', '../../../api/logic'); // I've also been trying ^^^ logic.py, if it matters request.send(null); console.log('testLogin ran'); step2(); } request.onreadystatechange = function () { if(request.readystate === 4) { if(request.status === 200) { console.log(request.responseText); } } } It still is hooked up to a URL POST … -
How to use AWS Simple Email Service (SES) in Django?
I'm trying to use this library to integrate my Django project with AWS SES. settings.py EMAIL_BACKEND = 'django_ses.SESBackend' AWS_ACCESS_KEY_ID = 'my_aws_access_key' AWS_SECRET_ACCESS_KEY = 'my_aws_secret_access_key' AWS_SES_REGION_NAME = 'us-west-2' AWS_SES_REGION_ENDPOINT = 'email.us-west-2.amazonaws.com' It throws the following error SESAddressNotVerifiedError: 400 Email address is not verified. <ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/"> <Error> <Type>Sender</Type> <Code>MessageRejected</Code> <Message>Email address is not verified. The following identities failed the check in region US-WEST-2: jpark1320@gmail.com, webmaster@localhost</Message> </Error> <RequestId>0220c0a0-741b-11e8-a153-475b5dfc6545</RequestId> </ErrorResponse> I can't even guess why is wrong on my codes. But, one thing might be a problem is send_mail(). I'm using trying to send an email to a user for password reset. I didn't use send_mail() in my codes directly, but instead I used password_reset, password_reset_done, and so on under django.contrib.auth.views since they let me send an email to a user for me. -
Django is there a way to use checkboxes in ChoiceField
I want to create a multiple choice field for user to select only one answer with the ChoiceField. The default widget is a drop down box which is not straight forward. I want to display all options directly and use the checkboxes for people to choose. I know there is a CheckboxSelectMultiple option but that accepts multiple answers. Is there a way to use checkboxes with multiple choice while I want only one answer? -
Search Database and print results Django Python
I'm very new to django/python and am in need of some help. So far I have a basic site with a database. Im trying to build a search page for the site where you enter what you're looking for in a search box. Then two of the fields for every entry in the database are scanned. If result found then i need the title field and body field to be shown on the page. The only way I've been able to make it work is by printing all the database entries on the same page as the search box. I can enter what i'm searching for in the box and get the result on the page. Problem is I need the search page to be blank and not have all the db entries listed prior to doing a search. I've been trying to figure this out for a couple weeks now but so far I haven't been able to make this work properly. I'm not looking for somebody to just hand me the answer, all I need is to be pointed in the direction of what I need to learn to be able to make this work. Thanks in advance. -
Voting on a model
I'm having trouble incrementing the vote_score attribute of my model every time it is voted on. This is my model: # idea model class Idea(models.Model): User = ('accounts.User') creator = models.ForeignKey(User, related_name='ideas', on_delete=models.PROTECT) title = models.CharField(max_length=100, null=True, blank=True) vote_score = models.BigIntegerField(default=0, null=True, blank=True) votes = VotableManager() #vote model class Vote(models.Model): user = models.ForeignKey(AUTH_USER_MODEL) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() create_at = models.DateTimeField(auto_now_add=True) vote = models.NullBooleanField() objects = VoteManager() class Meta: unique_together = ('user', 'content_type', 'object_id') @classmethod def votes_for(cls, model, instance=None): ct = ContentType.objects.get_for_model(model) kwargs = { "content_type": ct } if instance is not None: kwargs["object_id"] = instance.pk return cls.objects.filter(**kwargs) #manager _VotableManager(models.Manager): def __init__(self, through, model, instance, field_name='votes', extra_field='vote_score'): self.through = through self.model = model self.instance = instance self.field_name = field_name self.extra_field = extra_field self.name = model.title @instance_required def up(self, user, vote): with transaction.atomic(): if self.through.objects.filter(user=user, content_object=self.instance).exists(): c_type = ContentType.objects.get_for_model(self.instance) vote_obj = self.through.objects.get(user=user, object_id=self.instance.id, content_type=c_type) vote_obj.vote = vote vote_obj.save() self.instance.save() else: self.through(user=user, content_object=self.instance, vote=vote).save() if self.extra_field: setattr(self.instance, self.extra_field, F(self.extra_field)+1) self.instance.save() My goal is to have it so when the idea is created the creator automatically counts as 1 vote toward it so that falls under this view: # idea create view class IdeaCreateView(LoginRequiredMixin, CreateView): model = Idea form_class … -
create time stamps tuple python
I would like to create a tuple of time stamps. Where If I define a function like def time_stamps(starttime,endtime,intervals): #start time of tuple like 08:00:00 #End time of tuple like 21:00:00 #With Intervals of 60 or 30 0r 90 minutes. #example : if i call the function #x = time_stamps(08:00:00,21:00:00,00:30:00) #It should generate a tuple like this #('08:00:00','08:30:00','09:00:00',....,'20:30:00','21:00:00) I am lost.Please Help. Thank you -
Django Password_reset Email settings
I'm learning the Django and doing a project now , in the tutorial it used the django.core.mail.backends.console.EmailBackend to test the function , now I want to use my real email account to test the function . But after the setting , the smtp server always say the authorization problem (password 100% right) smtplib.SMTPSenderRefused: (553, b'Mail from must equal authorized user', 'webmaster@localhost') Hope someone can give me the suggestion , thanks. What I've done: complete the parameters in setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp server address here' EMAIL_PORT = 25 EMAIL_HOST_USER = 'the sender email here' EMAIL_HOST_PASSWORD = 'password here' EMAIL_FROM = 'Admin' So I want to ask , besides these setting , is there any other setting I need to do ? I.E. for the real email account , shall I write the "send email" function by myself again....? -
Django url passing unknown number of parameters
In Django, I am trying to pass unknown number of parameters to url in the template. To explain, I have urlpatterns in urls.py for example, urlpatterns = [ path('url1', views.url1, name = '<str:arg1>/'), path('url2', views.url2, name = '<str:arg1>/<int:arg2>/'), ] In my views.py, def url1(request): return render(request, 'template1.html', {'arg1': arg1}) def url2(request): return render(request, 'template2.html', {'arg1': arg1, 'arg2': arg2}) And to bind to href attribute in a tag in the templates, the template should look like: <!-- In template1.html --> <a href = "{% url url1 arg1 %}">Link</a> <!-- In template2.html --> <a href = "{% url url2 arg1 arg2 %}">Link</a> In this case, I want to merge template1.html and template2.html into template.html like following: <a href = "{% url url_name url_args %}">Link</a> And views.py: def url1(request): args = { 'url_name': url1, 'url_args': (arg1, ), } return render(request, 'template.html', args) def url2(request): args = { 'url_name': url2, 'url_args': (arg1, arg2), } return render(request, 'template.html', args) How do I pass url_args to the template? I tried passing url_args in tuple, list, and dictionary. But it wouldn't match prorperly. How should I pass url_args and code in template.html to make a tag to bind the link properly? -
Determining Form Fields after user input
I'm trying to make a json creator that is based off of a chosen schema. I know one solution would be to just model the fields off of the chosen schema's properties by just hardcoding the fields in but I want to make one form for all of the schemas that dynamically changes what those fields are and how many fields there are based off of parsing that schema and the values that gives me. I'm not sure if this is even possible let alone where to start. I'm not sure if I worded this entirely right, so if you have any clarification questions about this question don't hesitate to leave a comment and I'll try to edit the answer to be more clear to the best of my abilities. I'm using Python2.7 and Django 1.11 -
rendering a from from another app in the template of another django app
I am trying to render a newsletter app form on my pages app index.html template in the same project, but for some reason, the form is not displaying on the homepage. Please, can someone help as am fairly new to using Django. this is my pages\views.py from django.shortcuts import render from newsletter.forms import JoinForm def index(request): return render(request, 'pages/index.html') this is my newsletter\views from django.shortcuts import render from .models import Join from .forms import JoinForm def newsletter_signup(request): form = JoinForm(request.Post or None) if form.is_valid(): instance = form.save(commit=false) if Join.objects.filter(email=instance.email).exists(): print("This email already exists") else: instance.save() context = {'form': form,} return render(request, 'pages/index.html', context) this my pages\index.html template <form action=""> {% csrf_token %} {{ join }} <button class="waves-effect waves-light btn">Subscribe</button> </form> and this is my newsletter\forms.py from django import forms from .models import Join class JoinForm(forms.ModelForm): class Meta: model = Join fields = ['email'] def clean_email(self): email = self.cleaned_data.get('email') return email thanks. -
Associating a model with another model when saving it
I have the following code. The product is like this: There's a book list. On each book item is a form. This form saves a post and makes it related to this particular book. When you click a book item, you see a list of posts, all related to this book item. So far the book list works fine, saving post data works fine, and when you click a list, it (the DetailView) shows the list of posts (instead of book description, which is usually how DetailView is used) fine. What's not working is saving the post to be related to the particular book on whom is the form that saves the post. More simply, when you save a post, the post should be related to the book that the form is located in. I'd really appreciate your help. Thanks! views.py: class BookList(ListView): model = Book template_name='books/books.html' class PostForm(ModelForm): class Meta: model = Post # Previously I tried, unsuccessfully, this among others: # books = Book.objects.filter(book) # posts = Post.objects.filter(the_book=books) # model = posts fields = ['post'] widgets = { 'post': forms.Textarea() } def get_context_data(self, **kwargs): context = super(BookList, self).get_context_data(**kwargs) context['form'] = BookList.PostForm return context def post(self, request, *args, **kwargs): …