Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: how to get the second last object from database?
I have a model for news. I add news to the database with Django admin. Model Post consists of title, body and image. On the main.html page of my project i have a carousel with 3 slides. I already have some news in my database, and I want to display the last, the second last and so on images in that carousel. Help me please to do it. -
Jquery- Selecting individual word from a text
How do I select a word using Jquery and save that into DB. ie, Say I have the following in my page, "< p>This is a beautiful sentence < /p>" If I click on 'beautiful', I want to show a pop up option "add". If I click on "add", the word "beautiful" will be saved in my existing database of words. If i click it again It wont be saved, the database contains unique words. I am working in Django. -
Exception Value: Generic detail view TransactionDetailView must be called with either an object pk or a slug
This error arises when I attempt to visit the Transaction Detail page from my Transaction List page. I am using a UUID (primary=true) as the PK for the Transaction Detail page. I'm assuming it has something to do with my url path. Models.py class Transaction(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_transaction") order_id = models.CharField(max_length=36, blank=True, unique=True, default=uuid.uuid4, primary_key=True, editable=False) membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True, blank=True) amount = models.DecimalField(max_digits=100, decimal_places=2) success = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.order_id class Meta: ordering = ['-timestamp'] Urls.py path('transaction/<order_id>/', TransactionDetailView.as_view(), name='transaction_detail'), Views.py class TransactionDetailView(DetailView): model = Transaction slug_field = 'order_id' transaction_list.html {% if object_list %} {% for transaction in object_list %} <tr class="text-left"> <td ><strong><a href="{% url 'memberships:transaction_detail' transaction.order_id %}" class="text-dark">{{ transaction.user }}</a></strong></td> <td class="text-dark">{{ transaction.order_id }}</td> <td class="text-dark ">{{ transaction.timestamp }}</td> <td class="text-dark ">{{ transaction.success }}</td> <td class="text-dark">$ {{ transaction.amount }}</td> </tr> {% endfor %} {% else %} <p>There were no transactions found.</p> {% endif %} -
Reverse for 'update' with arguments '(1,)' not found. 1 pattern(s) tried: ['Manager/update/$']
After creating edit button in home.html, I've been getting this error all the time and have no idea how to resolve it. views.py def siteUpdate(request, id_): site=get_object_or_404(Site_data,id=id_) if request.POST=="POST": form=SiteForm(request.POST,instance=site) if form.is_valid(): form.log_name=request.user form.save() return redirect('Manager:home.html') else: form=SiteForm(instance=site) site = { 'form':form } return render(request,'Manager/siteform.html',sie) models.py class Site_data(models.Model): log_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) site_name = models.CharField(max_length=200) site_url = models.CharField(max_length=200) site_login = models.CharField(max_length=200, unique=True) password = models.CharField(max_length=200) urls.py app_name='Manager' urlpatterns = [ path('', views.home, name='home'), path('create/', views.siteCreate, name='create'), path('update/', views.siteUpdate, name='update') ] home.html {% for site in sites %} <td>{{site.site_name}}</td> <td>{{site.site_url}}</td> <td>{{site.site_login}}</td> <td>{{site.site_password}}</td> <td><a href="{% url 'Manager:update' site.id %}"><button type="button">Edit</button></a></td> {% endfor %} Thanks for help. -
How can I position a table at a particular x and y coordinate via reportlab
I have the following code which produces a pdf: def colr(x, y, z): return (x/255, y/255, z/255) import reportlab from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.utils import ImageReader from reportlab.platypus import SimpleDocTemplate, TableStyle, Paragraph, Image, Spacer, Frame, Paragraph from reportlab.platypus.tables import Table from reportlab.lib import colors from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER styles = getSampleStyleSheet() styleN = styles["BodyText"] styleN.alignment = TA_LEFT width, height = A4 logo = '/home/joel/myappointments/appointments/static/clinic/img/logo/logo.png' elements = [] print(f'Height={height}') imgw = imgh = 100 im = Image(logo, width=imgw, height=imgh) im.hAlign = 'LEFT' elements.append(im) headstyle = ParagraphStyle( name='MyHeader', fontName='Helvetica-Bold', fontSize=16, leading =10 ) doctorstyle = ParagraphStyle( name='MyDoctorHeader', fontName='Helvetica', fontSize=13, leading =10 ) data = [[Paragraph("Dr John Doe's ENT Clinic", style = headstyle)], [Paragraph("Dr John Doe", style = doctorstyle)], [Paragraph("ENT Specialist", style = doctorstyle)], [Paragraph("Registration No. ", style = doctorstyle)]] elements.append(Table(data, repeatRows=1)) line1 = ("Name", "Test", "Age", "20yr") line2 = ("MRD No.", "18","Date", "14-11-2018") line3 = ("No.","#", "Doctor", "Dr.John Doe") data=[line1,line2, line3] patientdetailstable = Table(data) patientdetailstable.setStyle(TableStyle([ ('BACKGROUND', (0, 0), (4, 0), '#CFEAD4'), ('BACKGROUND', (0, 2), (4, 2), '#CFEAD4'), ('BOX',(0,0),(-1,-1), 0.5, '#CFEAD4'), ('GRID',(0,0),(-1,-1), 0.5, colr(12, 43, 8)), ])) elements.append(patientdetailstable) elements.append(Spacer(1, 20)) # We use paragraph style because we need to wrap text. β¦ -
Django - Pagination in DRF returns an error in VueJS
Currently I'm using Vue in my JS file to consume my DRF APIs. Now when I add; 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 In the console, an error is being returned; It says; [Vue warn]: Error in render: "TypeError: status is null" (found in <Root>) TypeError: "status is null" In HTML: <select class="form-control" v-model="newJobRequest.status_of_the_job_request" required > <option v-for="status in statusOfTheJobRequests">[[status.type_of_status]]</option> </select> In JS: getStatusOfJobRequest: function() { this.loading = true; this.$http.get(/api/v1/status-of-the-job-request/) .then((response) => { this.statusOfTheJobRequests = response.data; this.loading = false; }) .catch((err) => { this.loading = false; console.log(err); }) } Due to this error, I am blocked on my task to build a pagination in the table. I've also used DataTables in my use case, but due to this error I can't continue and reverted back to the original state. In the Browsable APIs the pagination doesn't have any problems. I've been searching for answers for the last 2 days and didn't find any similar problems regarding this, afaik. -
Nginx with two Djangos with multiple locations
i've a problem serving Nginx with multiple locations under the same domain that uses two different Django installations. Here is my Nginx config : server { listen 80; server_name www.domain.net xxx.xxx.xxx.xxx; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # WebSocket support (nginx 1.4) proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location /shop { proxy_pass http://127.0.0.1:8088; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # WebSocket support (nginx 1.4) proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } and Django urls.py for this new location : from django.urls import include, path from django.contrib import admin from django.urls import path from oscar.app import application urlpatterns = [ path('shop/admin/', admin.site.urls), path('shop/i18n/', include('django.conf.urls.i18n')), path('shop', application.urls), ] But when Django tries under the same domain www.domain.net/shop the urls stop working only for this config... the other main still works correctly Any clue how to solve serving 2 different djangos under the same domain on different ports? Thanks guys! -
django form not saving updated value
I have the following form save process in my view: if request.method == "POST": form = PersonDetailForm(request.POST, request.FILES, instance=customer) if form.is_valid(): print(form.cleaned_data['first_name']) //prints corrected updated value saved_customer = form.save() print(saved_customer.first_name) //prints the old wrong value The problem is that the form is not saving the updated first name. When I print the cleaned_data is prints the correct updated value, but when I print the result of the saved form (saved_customer) it prints the old first name. What am I doing wrong? -
Updating a User's skills using ManyToManyField in django
I've been stuck on this for a few days (new to django) and can't figure out how to update skills for a specific user model using a ManyToManyField, while simultaneously updating a skill model containing a list of skills. Currently when I enter a value in my SkillForm, it updates the skill model properly and creates a dropdown list of skills for a given CustomUser in the admin. However, I can't figure out how to assign a SPECIFIC skill a particular user. Any help is appreciated. models.py: class Skill(models.Model): name = models.CharField(max_length =50, null=True, default='') def __str__(self): return self.name class CustomUserManager(UserManager): pass class CustomUser(AbstractUser): objects = CustomUserManager() skills = models.ManyToManyField(Skill, null=True, blank=True) position = models.CharField(max_length =50, null=True, default='') bio = models.CharField(max_length=300, null=True, default='') admin.py: class SkillsInline(admin.StackedInline): model = CustomUser.skills.through class SkillAdmin(admin.ModelAdmin): inlines = [SkillsInline ,] UserAdmin.fieldsets += ('Custom fields set', {'fields': ('position', 'bio', )}), class CustomUserAdmin(UserAdmin): model = CustomUser add_form = CustomUserCreationForm form = EditProfile inlines = [SkillsInline ,] admin.site.register(CustomUser, CustomUserAdmin) forms.py: class SkillForm(forms.ModelForm): name = forms.CharField() class Meta: model = Skill fields =('name' ,) def clean(self): cleaned_data = super().clean() name = cleaned_data.get('name') -
Django 2.1 SimpleTestCase, assertFieldOutput for DateField - AssertionError: ValidationError not raised
I have this simple Form (Django 2.1, Python 3.6.5). class RenewBookForm(forms.Form): renewal_date = forms.DateField( help_text="Enter a date between now and 4 weeks (default 3)." ) def clean_renewal_date(self): data = self.cleaned_data['renewal_date'] # Check if a date is not in the past. if data < datetime.date.today(): raise ValidationError(_('Invalid date - renewal in past')) # Check if a date is in the allowed range (+4 weeks from today). if data > datetime.date.today() + datetime.timedelta(weeks=4): raise ValidationError(_( 'Invalid date - renewal more than 4 weeks ahead')) # Remember to always return the cleaned data. return data And I have the test based on SimpleTestCase class: import datetime from django.forms import DateField from django.test import SimpleTestCase from django.utils import timezone from catalog.forms import RenewBookForm class RenewBookFormTest(SimpleTestCase): def test_renew_form_date_is_not_in_the_past(self): error_invalid = ['Invalid date - renewal in past'] past_date = datetime.date.today() - datetime.timedelta(days=1) valid_date = datetime.date.today() + datetime.timedelta(days=21) valid = { valid_date: valid_date } invalid = { past_date: error_invalid } self.assertFieldOutput(DateField, valid, invalid) Error, after running this test: Traceback (most recent call last): File "locallibrary/catalog/tests/test_forms.py", line 53, in test_renew_form_date_is_not_in_the_past self.assertFieldOutput(DateField, valid, invalid) File "~/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/test/testcases.py", line 660, in assertFieldOutput required.clean(input) AssertionError: ValidationError not raised What is wrong in this test? Thank you. -
How to connect Django with my Discord Bot
I'm trying to create a dashboard for my Python discord bot but running into some issues.. I'm using Django and trying to use an oauth url with the django-allauth module. I copied the url generated by discord but when i try to use it to connect it tells me "Social Network Login Failure An error occurred while attempting to login via your social network account." after logging in. Any ideas how to fix? -
Call same function on multiple urls django
urls.py url(r'^level/ajax/reload/$', views.ajax_change_status, name='ajax_change_status'), url(r'^level/(\d+)/ajax/reload/$', views.ajax_change_status, name='ajax_change_status'), url(r'^level/(\d+)/(\d+)/ajax/reload/$', views.ajax_change_status, name='ajax_change_status'), In my urls.py i have these urls.Im trying to call an ajax function in my view basically to update the notification badge to 0 after user clicks on the bell icon.The notification badge is in the base.html template.Im calling the url with the name "ajax_change_status" . I want all these urls to call the same ajax funtion.Is it possible to do this or is there a better way?Im getting a 500 server error when i click on the bell icon from the second and third url My ajax function in views.py: def ajax_change_status(request): if request.is_ajax(): try: Notification.objects.filter(receiver=request.user) .update(viewed=True) Addnotify.objects.filter(receiver=request.user) .update(viewed=True) FollowNotify.objects.filter(receiver=request.user) .update(viewed=True) HubNotify.objects.filter(receiver=request.user) .update(viewed=True) return JsonResponse({"success": True}) except Exception as e: print(e) return JsonResponse({"success": False}) My ajax jquery: var clicks = 0; $("#notify").on('click', function () { $.ajax({ url: 'ajax/reload/', data: { }, success: function (data) { if (data.success) { console.log('ajax call success.'); $('#badge').html('0') $('#headnotify').html('NOTIFICATIONS (0)') // here you update the HTML to change the active to innactive }else{ console.log('ajax call not success.'); } clicks++; } }); }); Seems like it is not getting into the ajax function when i try it on the second and third url!! -
Django and technical fields
I'm building a data model. I want that each model has some technical fields like: created and updated. I don't like to add those fieds to each model (you know...DRY). I tried to build a parent class with the created and updated fields, and inherit it in the other models, but Django's ORM does not put created and updated fields in the table of the model, instead it creates another table for the two fields and link it to the model via foreign key. That is not what I want. Is there a feasible way? -
How to display array value in Django template?
I have the following array and would like to display Monday in the template. DAYS = ((0, "Saturday"), (1, "Sunday"), (2, "Monday"), (3, "Tuesday"), (4, "Wednesday")) I can display (2, "Monday") by using {{ DAYS.2 }} but I was unable to display only Monday as value. Thank you! -
ModuleNotFoundError: No module named 'xxxdjango'
I've been looking thoroughly before asking this question but couldn't find the answer on Stack overflow. Guy below had similar problem but he didn't send any info: [ModuleNotFoundError: No module named 'firstappdjango' I've launched default app without problems and got django screen etc. I am following a tutorial now and I started simple app with some HTML response. I get error called ModuleNotFoundError: No module named 'adamprojectdjango' when I want to run server. What i've checked/some info my app is called adamproject app installed in settings.py INSTALLED_APPS = [ 'adamproject' 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] directories look as below /home/none/eclipse-workspace/test5 βββ adamproject β βββ migrations βββ test5 βββ pycache app config file: from django.apps import AppConfig class MysiteConfig(AppConfig): name = 'adamproject' -
Develop a standalone desktop application using Python
I am new to standalone application development in Python. I would like to develop a Standalone Desktop Application using Python, which pops up a window (having various fields and buttons ,etc- like a Forms design in C#) , it should upload 3 files on a 3 different buttons and verifies if the data of the file is correct. Since Python is vast, I would like to know if there is any Framework or tool that can be used with Python or can i do it exclusively in pure python? Also, can i use Django in this case or is it only for front end web development? Thank you. -
Database model custom JSONField values persisting between test cases
I'm using a Django database model to store objects corresponding to a remote ticket service. In testing this model, I'm running several tests to make sure that log messages work correctly for the database model - I'm using Django-nose to run these tests. The database model looks something like this, using the JSONField from this StackOverflow answer with a small modification to support lists as well as dicts: class TicketEntity(django.db.models.Model) tickets = JSONField(null=True, blank=True, default=[], serialize=True) queued_ticket_data = JSONField(null=True, blank=True, default=[], serialize=True) ... @classmethod def create(cls, *args, **kwargs): instance = cls(*args, **kwargs) instance.save() return instance def queue_output_for_ticket(self, log_data): self.queued_ticket_data += [log_data] self.save() def push_ticket(self): self.tickets += [self.queued_ticket_data] self.queued_ticket_data = [] self.save() return True The tests (in the order they appear to get run) look like this: def test_ticket_entity_push_ticket(self): entity = TicketEntity.create() entity.queue_output_for_ticket("log output") entity.queue_output_for_ticket("more log output") entity.push_ticket() self.assertEquals(entity.tickets, [[log_data, log_data_1]]) self.assertFalse(entity.queued_ticket_data) def test_ticket_entity_queue_output_for_ticket(self): entity = TicketEntity.create() log_data = "Here's some output to log.\nHere's another line of output.\nAnd another." entity.queue_output_for_ticket(log_data) self.assertEquals(entity.queued_ticket_data, [log_data]) The first test passes, perfectly fine. The second test fails on that assert statement, because the entity.queued_ticket_data looks like this: ["log output", "more log output", "Here's some output to log.\nHere's another line of output.\nAnd another."] Those first two elements β¦ -
Database still in use after a selenium test in Django
I have a Django project in which I'm starting to write Selenium tests. The first one looking like this: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys from core.models import User from example import settings BACH_EMAIL = "johann.sebastian.bach@classics.com" PASSWORD = "password" class TestImportCRMData(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.webdriver = webdriver.Chrome() cls.webdriver.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.webdriver.close() cls.webdriver.quit() super().tearDownClass() def setUp(self): self.admin = User.objects.create_superuser(email=BACH_EMAIL, password=PASSWORD) def test_admin_tool(self): self.webdriver.get(f"http://{settings.ADMIN_HOST}:{self.server_thread.port}/admin") self.webdriver.find_element_by_id("id_username").send_keys(BACH_EMAIL) self.webdriver.find_element_by_id("id_password").send_keys(PASSWORD) self.webdriver.find_element_by_id("id_password").send_keys(Keys.RETURN) self.webdriver.find_element_by_link_text("Users").click() When I run it, the test pass but still ends with this error: Traceback (most recent call last): File "C:\Users\pupeno\Documents\Eligible\code\example\venv\lib\site-packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.OperationalError: database "test_example" is being accessed by other users DETAIL: There is 1 other session using the database. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2018.2.4\helpers\pycharm\django_test_manage.py", line 168, in <module> utility.execute() File "C:\Program Files\JetBrains\PyCharm 2018.2.4\helpers\pycharm\django_test_manage.py", line 142, in execute _create_command().run_from_argv(self.argv) File "C:\Users\pupeno\Documents\Eligible\code\example\venv\lib\site-packages\django\core\management\commands\test.py", line 26, in run_from_argv super().run_from_argv(argv) File "C:\Users\pupeno\Documents\Eligible\code\example\venv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\pupeno\Documents\Eligible\code\example\venv\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Program Files\JetBrains\PyCharm 2018.2.4\helpers\pycharm\django_test_manage.py", line 104, in handle failures = TestRunner(test_labels, **options) File "C:\Program Files\JetBrains\PyCharm 2018.2.4\helpers\pycharm\django_test_runner.py", line 255, in run_tests extra_tests=extra_tests, **options) File β¦ -
get_queryset() from a js text input
In this step I'm trying to avoid making a form to send data over to django from the frontend. Ideally I would like to pass a simple string to the queryset with an onclick button, so I can make the tag filters on my Post model and show the ones with the tags from the string input. (just send the string to the queryset, I can deal with the split() and strip() to make it valid) The simplified html would be something like <input type="text" name="tag_filter"> <button type="button" onclick="Tag_Filter()">Filter</button> And the ListView class PostListView(ListView): model = Post #.objects.filter(tags__name__in=["black&white", "red"]).distinct() template_name = 'post/home.html' # <app>/<model>_<viewtype>.html #queryset = Post.objects.all() context_object_name = 'posts' #ordering = ['-date_posted'] def get_queryset(self): tag_list = #the return from the Tag_Filter() js return Post.objects.filter(tags__name__in=tag_list).annotate(num_tags=Count('tags')).filter(num_tags__gte=len(tag_list)).order_by('-date_posted').distinct() -
Method Not Allowed (POST): /contact/sent/
I am getting this method not allowed(post), like I can't post my forms.what could I be doing wrong.I am new to django. Could my url.py be wrong or my form-id is incorrect that doesn't enable the posting of data. views.py class ContactUsView(ContactFormView): """ Contact Us Form View """ form_class = ContactUsForm def get_success_url(self): return reverse('messaging:contact_form_sent') def clear_notification(request): """ Clears the notification for a given user""" Notifications.objects.filter(user=request.user).delete() return redirect(reverse('accounts:dashboard', args=(request.user,))) urls.py urlpatterns = [ path( 'contact/', views.ContactUsView.as_view(), name='contact_form'), path( r'contact/sent/', TemplateView.as_view( template_name='contact_form/contact_form_sent.html'), name='contact_form_sent'), path(r'clear/', views.clear_notification, name='clear_notification'), ] contact_form.html <div class="row"> <form id='ContactUsForm' method='post' action={% url 'messaging:contact_form_sent' %}><br> {% csrf_token %} <div class="col-md-6"> <div class="form-group"> {% csrf_token %} <input type="text" class="form-control input-upper" id="fullname" placeholder="John Doe" name="fullname"> </div> </div> <div class="col-md-6"> <div class="form-group"> {% csrf_token %} <input type="email" class="form-control input-upper" id="email" placeholder="Email" name="email"> </div> </div> </div><br><br> <div class="row"> <div class="col-md-6"> <div class="form-group"> {% csrf_token %} <input type="text" class="form-control input-upper" id="subject" placeholder="Subject" name="subject"> </div> </div> </div><br> <div class="row"> <div class="col-md-10"> <div class="form-group"> {% csrf_token %} <textarea class="form-control input-upper" id="message" placeholder="Message" name="message"></textarea> </div> {% csrf_token %} <button type="submit" class="btn btn-primary btn-send-contact" value="SUBMIT">SEND</button> </div> </div><br><br> </form> </div> </div> {% endblock %} -
Design Pattern Django
i would like know if exist a pattern for design apps on django example. The apps is into folder with name "apps". the html files is into folder "templates" .. .. etc.. the tutorial that i reAd is PEP 8 in this case dont is a patter for desing spetial for Django. PEP8 only say about the identation, names for def and class..etc.. Please any suggest or link for read more about this theme.. thanks..!! -
Django: Fastest way to query & group a queryset by a ManyToManyField
I have two models - a Product & Category. In my template, I want to display the products by the Category. Slow solution The most basic way to do this, query the Categories and in the template loop over the products. {% for category in object_list %} {% for product in category.products.all %} < html to display the product > {% endfor %} {% endfor %} This results in hundreds of queries and is very slow. Question What would be better way to handle this query so that there are as few queries as possible with a faster load time? -
NoReverseMatch: Reverse for 'topics' with arguments '(3,)' not found. 1 pattern(s) tried: ['topics/$']
My question is about redirection again to a /topics/[id_number_for_topic] page where all entries for topic are located. When I end an entry editing in /edit_entry/[id_number_for_entry] and click the button the error is occured as below: Reverse for 'topics' with arguments '(3,)' not found. 1 pattern(s) tried: ['topics/$'] This number 3 indicates for a topic id. I guess the problem is with return instruction in views.py > edit_entry() or in regex expression My code: views.py def edit_entry(request, entry_id): """Edycja wpisu""" entry = Entry.objects.get(id=entry_id) topic = entry.topic if request.method != 'POST': form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topics', args=[topic.id])) context = {'entry': entry, 'topic': topic, 'form': form} return render(request, 'edit_entry.html', context) urls.py url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic'), url(r'^edit_entry/(?P<entry_id>\d+)/$', views.edit_entry, name='edit_entry'), models.py class Topic(models.Model): """Temat poznawany przez usera""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Zwraca reprezentacje modelu w postaci ciagu text.""" return self.text class Entry(models.Model): """Konkret informacje o postepie w nauce""" topic = models.ForeignKey(Topic) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): return self.text[:50] + "..." edit_entry.html {% block content %} <p><a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></p> <h3>Edycja wpisu:</h3> <form action="{% url 'learning_logs:edit_entry' entry.id %}" method='post'> {% csrf_token %} {{ β¦ -
django-moderation inherited fields not moderated
I have a class which extends a class from a 3rd party package (named django-scheduler). from schedule.models import Event from moderation.db import ModeratedModel class Event(Event, ModeratedModel): more_fields = models.TextField() ... The problem is now, that in the django Admin only the fields of my own Event class are getting "moderated". The inherited fields of the Event class from the scheduler package aren't shown in the moderated object... I guess this problem is quite specific for this 3rd party package django-moderation... Or are there any ideas how to tell the ModeratedModel class also to have a look at the "foreign" Event fields? -
supervisord as service and sensitive environment variables
I'm using supervisor to monitor a gunicorn process for a Django application. My config: [program:app] environment= SETTINGS="%(ENV_SETTINGS)s", DB_NAME="%(ENV_DB_NAME)s", DB_PASS="%(ENV_DB_PASS)s", DB_USER="%(ENV_DB_USER)s", EMAIL_HOST_PASSWORD="%(ENV_EMAIL_HOST_PASSWORD)s", SECRET_KEY="%(ENV_SECRET_KEY)s" command=/home/app/bin/gunicorn_start user=username autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/app/logs/gunicorn-error.log I have the environment variables defined in /etc/bashrc. These variables contain sensitive data (per recommendation of the "Two Scoops of Django" book to store them in the environment) I have verified with the env command that my variables are present in the environment. Supervisor is throwing an error that it can not access my environment variables: ERROR: CANT_REREAD: Format string '\nSETTINGS="%(ENV_SETTINGS)s"...' for 'environment' contains names ('ENV_SETTINGS') which cannot be expanded. Available names: ENV_HOME, ENV_LANG, ENV_LOGNAME, ENV_PATH, ENV_SHELL, ENV_USER, group_name, here, host_node_name, process_num, program_name in section 'program:app' (file: '/etc/supervisord/supervisord.conf') This problem has been described before (link). When launched as a service, supervisor can not access variables defined in shell configuration files by a particular user. Indeed those variables that it lists as available are just a small subset of what is available to me if I run the env command. Where should I define my secrets as env variables? Should I take them out of /etc/bashrc and define them in the supervisor config file? Or in the gunicorn_start script even (/home/app/bin/gunicorn_start)?