Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authenticate Django site with Wordpress site
I am writing a Django application and I need to sign in to it with Wordpress just like other sites can sign in with social networks. I would like my django app to provide a button that I click to take me to my wordpress site where an authenticate button or login page is waiting that redirects me back to my django site and signs me in. I will also need to have access to the wordpress user details within my django app. Does anybody know a suitable wordpress plugin and complimentary django library for such a job? -
django dynamic forms based on query result in one template
I have a requirement which a bit new on this django framework. i have been searching alot but couldnt find. <h2> Main Table </h2> ID = Primary Key Position= CharField <h2> Child Table </h2> position=foreignkey(main table) employee=CharField attendance=CharField Scenario I have a listview with following data as an example in the template. <Table> <th> ID </th> <th> Position</th> <th> Update </th> <td>1</td> <td>Manager</td> <td><a href="#">Click </a> </td> <tr></tr> <td>2</td> <td>Staff</td> <td><a href="#">Click </a> </td> </table> I need to create dynamic forms in the update template based on child table rows in a data grid to update attendance -
Django: how to create_or_get excluded field in forms?
I have a form with 2 fields: one called 'field' the other called 'exclude'. 'exclude' is excluded. class ExampleForm(ModelForm): class Meta: model = Example fields = ['field', 'exclude'] exclude = ('exclude') I want to use this as part of a multi-form submit, and may or maybe already exist in Example Manager. So I wish to use get_or_create(). So I made a test for using get_or_create(), however, I am not sure whether it is the right way of going about solving the issue? def test_valid_creation(): form = self.exampleFrom(data_neg_exclude) if self.form.is_valid(): form_inst = self.form.save(commit=False) data = model_to_dict(form_inst) data.update({'exclude': 'yes please'}) Example.objects.get_or_create(**data) -
Highlight the given search string in the web page using django
I thought I could get a answer to this but couldn't :( How to highlight all the occurrences of the string the the content of the web-page using django. This is similar to the ctrl+F we usually do in the browser to search for a string. I found an answer for this in JS ,but need an answer using django here. This is my views.py to display the content of the posts.The search query would be from the "detail.html" file. views.py def post_detail(request,id=None): #retrieve the data instance = get_object_or_404(Post, id=id) if instance.draft or instance.publish > timezone.now().date(): if not request.user.is_staff or not request.user.is_superuser: raise Http404 query = request.GET.get("q") #need your help after this share_string = quote_plus(instance.content) context = { "title": instance.title, "instance": instance, "share_string": share_string, } return render(request, "detail.html", context) Waiting for an answer... :) -
Create Many to Many Create/Update in modelSerializer with through table
Here are my models from django.db import models class Person(models.Model): name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) persons = models.ManyToManyField(Person, through='Membership') class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) fee = models.IntegerField() At Serializer level, i want to save Members and Groups which are M2M related to person through Membership i am trying something like that. class GroupMembershipSerializer(ModelSerializer): class Meta: model = Membership fields = ('person', 'fee', ) class GroupCreateSerializer(ModelSerializer): memberships = GroupMembershipSerializer(many=True, required=False) def create(self, validated_data): person_data = validated_data.pop('memberships') fee = validated_data.pop('fee') # Stuck here ! What should i do here ? group = Group.objects.create(**validated_data) for person in person_data: d=dict(person) Membership.objects.create(group=group, person=d['person']) return group def update(self, instance, validated_data): person_data = validated_data.pop('memberships') for item in validated_data: if Group._meta.get_field(item): setattr(instance, item, validated_data[item]) Membership.objects.filter(group=instance).delete() for person in person_data: d=dict(person) Membership.objects.create(group=instance,person=d['person']) instance.save() return instance class Meta: model = Group class GroupCreateModelViewSet(ModelViewSet): serializer_class = GroupCreateSerializer queryset = Group.objects.all() How would it work to save fee in that table too, except that it is working -
NOT NULL constraint failed: Django
I'm using Django 2.0 I have a model with field to store transaction id, which is not a foreign key to any table but just a column to record the transaction id. class TransactionRecords(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) transaction_id = models.CharField(max_length=100, default=None) But this is giving error as IntegrityError NOT NULL constraint failed: transactionrecords.authorization_id How can I setup Django not to treat transaction_id as foreign key? -
Django Rest Framework (DRF 2) Homepage Authentication
Just started with Django and DRF 2 (Sadly from 15 years of only PHP and Javascript background). Would love to see how to password-protect DRF's homepage as an example of how to get past the ViewSet confusion I am having right now (I'm used to the resource and individual routing style of Laravel). I guess I can go a bit faster learning the platform if I can see how it is done. Would also like to see how to put in additional API backends to the system, if you have time. Thanks in advanced. -
Django ModelForm foreign key filtering
I'm trying to filter foreign key field selections in my model form, but form isn't working. My scripts: forms.py from django import forms from .models import Album, Song class SongCreateForm(forms.ModelForm): class Meta: model = Song fields = [ 'album', 'name', 'is_favorite' ] widgets = { 'album': forms.Select(attrs={'class': 'form-control'}), 'name': forms.TextInput(attrs={'class': 'form-control'}), 'is_favorite': forms.CheckboxInput(attrs={'class': 'form-check-input'}), } def __init__(self, user, *args, **kwargs): super(SongCreateForm, self).__init__(*args, **kwargs) self.fields['album'].queryset = Album.objects.filter(owner=user) views.py from django.views.generic import CreateView class SongCreateView(CreateView): template_name = 'music/song_create.html' success_url = '/songs/' def get_form(self, form_class=None): form_class = SongCreateForm(user=self.request.user) return form_class print(form_class.errors.as_data()) print(form_class.is_valid()) song_create.html {% extends 'base.html' %} {% block content %} <form method="post">{% csrf_token %} {% if form.errors %} <p>{{ form.errors }}</p> {% endif %} <div class="form-group"> <label for="{{ form.album.id_for_label }}">Album</label> {{ form.album }} </div> <div class="form-group"> <label for="{{ form.name.id_for_label }}">Name</label> {{ form.name }} </div> <div class="form-check"> <label for="{{ form.is_favorite.id_for_label }}" class="form-check-label"> {{ form.is_favorite }}Favorite </label> </div> <button type="submit" class="btn btn-primary" value="Save">Add</button> </form> {% endblock %} Filtering queryset of 'album' field is working correctly. It is displaying only albums that are associated with authenticated user, but when I click submit in form browser doesn't redirect me to success url and song isn't added to database. I've added two print statements at the end … -
Using transaction.atomic to roll back recursive form validation + save
I want to validate and save a json "tree" recursively (process_response function below). If if any leaves in the tree are invalid, I want to roll back all the saved leaves so far. Here's an example of my approach: @staticmethod def process_response(post_data): """ brief pseudocode function to illustrate resursive form.save() """ if is_leaf is True: if not form.is_valid(): return HttpResponse(status=400) else: form.save(post_data) return HttpResponse(status=200) else: # is not a leaf, so must be a branch for child_data in post_data.children result = MyClass.process_response(child_data) if result.status_code != 200: return result def post(self, request, *args, **kwargs): post_data = process_post_data(request) # json decoding, validation, etc with transaction.atomic(): try: result = MyClass.process_response(post_data) if result.status_code != 200: raise DatabaseError except: return result return result Will wrapping the call to the process_response function in transaction.atomic and raising a DatabaseError if any leaves don't validate allow me to do this? Or is there another better way of validating and saving data in a "tree" structure? -
Django Testing: django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist:
I get the error from the ProductTestCase: django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: Product has no name_text It would be great to know how to fix this issue and why it only occurs when on Foreign keys. I am sure that the Department is fine it just it does not seem to be passed over to Product. I have added in Department test as well, it works fine. Thank you for your time. I know of this page here, but it appears not to point out how to fix the issue, but catch the issue. Which is useful but knowing how to stop it in the first place is also useful. Department Test class DepartmentTestCase(ModelTestCase): def setUp(self): super(DepartmentTestCase, self).setUp() self.department_form = self.get_department_form(department_name_text=self.department_name) def test_valid_input(self): self.assertTrue(self.department_form.is_valid()) Product Test (updated: change to match comment improvement) class ProductTestCase(ModelTestCase): @classmethod def setUpTestData(cls): super(ProductTestCase, cls).setUpTestData() def setUp(self): super(ProductTestCase, self).setUp() self.product_data = {'barcode_text': self.barcode } department_inst = Department.objects.create(department_name_text=self.department_name) maker_inst = Maker.objects.create(maker_name_text=self.maker_name) self.product_data.update({'name_text': department_inst, 'from_maker': maker_inst}) def test_valid_input(self): product_form = ProductForm(self.product_data) self.assertTrue(product_form.is_valid()) def test_form_save(self): product_form = ProductForm(self.product_data) product_instance = product_form.save() #I believe the error occurs when the form is saved self.assertEqual(Product.objects.get(pk=product_instance_id), product_instance) Department Form class DepartmentForm(ModelForm): field_names = {'department_name_text': 'Department Name'} class Meta: model = Department fields = ['department_name_text'] def __init__(self, *args, … -
How to convert django form data into pdf?
I have a form that takes user request for what kind of service they are looking for and when the users click submit, I want the form data to get converted into a pdf file. And also I want that pdf to be sent to my email. How can I achieve this? Code sample is highly appreciated. Thanks in advance. -
delete and update method not workin in not django rest framework
I am trying to build an API using DRF, get() and post() method is working fine but the delete and update methods are not working. I am getting this error, can anyone please help me to rectify this error is coming. TypeError: delete() missing 1 required positional argument: 'pk' views.py file class MenuList(APIView): def get(self, request): menu = Menu.objects.all() serializer = MenuSerializer(menu, many=True) return Response(serializer.data) def post(self, request): serializer = MenuSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): menu = self.get_object(pk) menu.delete() return Response(status=status.HTTP_204_NO_CONTENT) class MenuDetail(APIView): """ Retrieve, update or delete a Menu instance.""" def get_object(self,pk): try: return Menu.objects.get(pk=pk) except Menu.DoesNotExist: raise Http404 def get(self, request,pk): menu = self.get_object(pk) menu = MenuSerializer(menu) return Response(menu.data) def put(self, request, pk): menu = self.get_object(pk) serializer = MenuSerializer(menu, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_404_BAD_REQUEST) def delete(self, request, pk): menu = self.get_object(pk) menu.delete() return Response(status=status.HTTP_204_NO_CONTENT) class MenuItemList(APIView): def get(self, request): menuitem = MenuItem.objects.all() serializer = MenuItemSerializer(menuitem, many=True) return Response(serializer.data) def post(self, request): serializer = MenuItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): menuitem = self.get_object(pk) menuitem.delete() return Response(status=status.HTTP_204_NO_CONTENT) class MenuItemDetail(APIView): def get_object(self,pk): try: return MenuItem.objects.get(pk=pk) except MenuItem.DoesNotExist: raise Http404 def … -
Django template rendering does not display my data
I just can't solve my problem, don't see where/what do i wrong. Here is my model class Account(models.Model): uuid = ShortUUIDField(unique=True) name = models.CharField(max_length=80) desc = models.TextField(blank=True) address_one = models.CharField(max_length=100) address_two = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50) state = models.CharField(max_length=2) phone = models.CharField(max_length=20) owner = models.ForeignKey(User, on_delete=models.DO_NOTHING,) created_on = models.DateField(auto_now_add=True) Here is my view class AccountList(ListView): model = Account @login_required() def account_detail(request, uuid): account = Account.objects.get(uuid=uuid) if account.owner != request.user: return HttpResponseForbidden() variables = { 'account': account, } return render(request, 'accounts/account_detail.html', variables) Im tried to render it in my accaunt_detail template with following code: {% extends 'base.html' %} {% block content %} <div id="content-container" class="container p-none"> <div id="ad-container"> <div id="gi-container" class="ad-container"> <div class="row gi-body"> <div class="col-md-9"> <h5 class="gi-sh">Description</h5> <p>{{ account.desc }}</p> </div> <div class="col-md-3"> <h5 class="gi-sh">Address</h5> <p class="nm">{{ account.address_one }}</p> <p class="nm">{{ account.address_two }}</p> <p class="nm">{{ account.city}}, {{ account.state }}</p> <p class="nm">{{ account.phone}}</p> </div> </div> </div> </div> {# List Contacts #} {# List Communications #} </div> {% endblock %} But i get just empty Page. I do not get any errors, like everything works fine but the user details are not displayed. I have created ~15 users, so i have users in my database. -
Persistence issues with checkboxes
My Goal Is to create a shopping webpage where users can filter through the product selection by checking checkboxes. Instead of having a "submit" button I wanted the page to submit as soon as the user checked the checkbox. Example: the "refine by" section on Amazon. My Solution The best way would have been to use AJAX however I opted for a simple javascript / jquery function instead: $(":checkbox").change(function () { $('#product-filters').submit() }); Clicking the checkbox would correctly refresh page and apply filters, however the checkbox would appear un-checked to the user. So in Django I implemented following workaround: filters = request.GET.getlist('filters', None) selected_filters = [] try: for f in filters: selected_filters.append(int(f)) except TypeError: selected_filters = None return { # ..... 'selected_filters': selected_filters, } And then in my template: <input {% if filter.id in selected_filters %}checked="checked"{% endif %} ... all my other attrs></input> My Issue While all of the above works correctly I now have the issue that if a user clicks on a checked checkbox in order to uncheck it, it will simply refresh the page and keep it checked, with that filter applied. How should I go about fixing this? -
Converting a table from html file to pdf using xhtml2pdf
Hi guys I am having a problem using xhtml2pdf. I am following a tutorial and it worked (note: the data in the tutorial is hardcoded). So I change a bit of the code from the tutorial so I can fetch data from a database using django-rest-framework. When I run the project there were no errors but I typed the url to see my pdf file, its error 404. here is my views.py class GeneratePdf(ReadOnlyModelViewSet): queryset = DirectoryTb.objects.all() serializer_class = DirectoryTbSerializer def get(self, request, queryset, *args, **kwargs): pdf = render_to_pdf('directory.html', queryset) return HttpResponse(pdf, content_type='application/pdf') here is my urls.py router = DefaultRouter() router.register(r'^pdf', GeneratePdf) urlpatterns = router.urls -
Vue.js in Django Templates
I am trying to use Vue.js in Django templates. One such template is the following: {% load static %} <!DOCTYPE html> <html> <head> </head> <body> <div id="myApp"> <span>Hello [[ message ]]</span> <div id="map"></map> </div> <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <script src="https://v1.vuejs.org/js/vue.js"></script> <script src="{% static 'js/script.js' %}"></script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC62HW0L7DIhL7oLbWvCEekHOkPWdxBPwk&callback=initMap"></script> </body> </html> I changed Vue's interpolation delimiters to [[ ]] to avoid conflict with Django. My script.js looks as follows: $(function() { var app = new Vue({ el: '#myApp', delimiters: ['[[', ']]'], data: { message: 'Hello, world!' } }); }); Unfortunately, the HTML rendered contains [[ message ]]. Has anyone else faced a similar issue? -
Django, How to avoid 'matching query does not exist'
views.py try: testmodel2 = TestModel_2.objects.get(description='a') except TestModel_2.DoesNotExist: testmodel2 = None models.py @python_2_unicode_compatible class TestModel_2(models.Model): description = models.CharField(max_length=34) created = models.DateTimeField(auto_now_add=True) def __str__(self): return "TestModel %s" % self.description Question: Why though I set DoesNotExist, myapp.models.DoesNotExist: TestModel_2 matching query does not exist. is occurred? -
Include keyword in url.py not working without app_name(Django 2.0)
When I try to use the include keyword in url.py to reverse match url in model.py reverse("products:detail", kwargs={"slug": self.slug} it says: Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. I see that in Django 2.0, you have to provide app_name with namespace. As I have created my app with python manage.py startapp products, I thing my app name is products. My url.py: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from .views import hello_world, home_page, about_page, contact_page, login_page, register_page urlpatterns = [ url(r'^hello/$', hello_world), url(r'^$', home_page), url(r'^admin/', admin.site.urls), url(r'^about/$', about_page), url(r'^contact/$', contact_page), url(r'^login/$', login_page), url(r'^register/$', register_page), url(r'^products/', include(products, namespace='products')), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` And my products/model.py: import random import os from django.db import models from django.db.models.signals import pre_save, post_save from django.urls import reverse from .utils import unique_slug_generator def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(filepath) return name, ext def upload_image_path(instance, filename): new_filename = random.randint(0, … -
NOT NULL constraint failed error when populating foreign key field
I'm trying to run a script I wrote to move some data from json files into my database, and keep getting the same error. Traceback: Traceback (most recent call last): File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: clan_participant.completed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "participant_updater.py", line 32, in <module> message = participant_updater() File "/home/jamtime/clansite/database_updaters.py", line 548, in participant_updater update_db() File "/home/jamtime/clansite/database_updaters.py", line 512, in update_db character=char_obj File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 653, in create return super(RelatedManager, self.db_manager(db)).create(**kwargs) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 923, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 962, in _do_insert using=using, raw=raw) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/query.py", line 1076, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1107, in execute_sql cursor.execute(sql, params) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) … -
Unaable to install django2 on python
I install ubuntu And use python 3 When i want install django 2 I have an error : no module named 'django' Thankyou for your attention -
ImportError: no module named website.settings
ImportError: module not found When attempting top run a Django project on my virtual enviornment, Give me this error, project works on original computer. -
DJango + nginx + gunicorn: how to stop caching
I am running Django 2.0 using gunicorn on nginx server. All my pages are not reflecting the changes immediately. How to stop caching the below are my files: nginx.conf server { listen 80; server_name sample.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/testapp/testapp_project/test_artciles; } location /media/ { root /home/testapp/testapp_project/test_artciles; } location / { include proxy_params; proxy_pass http://unix:/home/testapp/testapp_project/test_artciles.sock; } } Django settings.py import os from django.contrib import messages BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'ssdjhasjdkhjaskdhkajsdhkjasdhkjh' DEBUG = True ALLOWED_HOSTS = ['xx.xxx.xx.xxx','127.0.0.1'] INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django_extensions', # local apps 'articles', 'fcm_django', 'corsheaders', 'rest_framework', ) MIDDLEWARE = ( 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'webarticles.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.join(BASE_DIR, 'templates')), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'webarticles.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'test.sqlite3'), } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ =True AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL … -
Forms are not shown
Forms are not shown.How should I show forms in one url?I wanna make a writing comment&recomment system.I wrote in comment.html {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>COMMENT</title> </head> <body> <div> <h2>{{ object.text }}</h2> </div> <div id="comment-area"> {% for comment in post.comment.all %} <div class="media m-3"> <div class="media-body"> <h5 class="mt-0"> <span class="badge badge-primary badge-pill">{% by_the_time comment.created_at %}</span> {{ comment.name }} <span class="lead text-muted">{{ comment.created_at }}</span> <a href="{% url 'recomment' comment.pk %}"Reply</a> </h5> {{ comment.text | linebreaksbr }} {% for recomment in comment.recomment.all %} <div class="media m-3"> <div class="media-body"> <h5 class="mt-0"> {{ recomment.name }} <span class="lead text-muted">{{ recomment.created_at }}</span> </h5> {{ recomment.text | linebreaksbr }} </div> </div> {% endfor %} </div> </div> {% endfor %} </div> <form action="" method="POST" enctype='multipart/form-data'> {% for field in form %} <div class="form-group"> {{ field.errors }} <label for="{{ field.id_for_label }}"> {{ field.label }} </label> {{ field }} </div> {% endfor %} {% csrf_token %} <input class="btn btn-primary" type="submit" value="comment"> </form> </body> </html> in views.py class DetailView(generic.DetailView): model = POST template_name = 'comment.html' class CommentCreateView(generic.CreateView): model = Comment form_class = CommentCreateForm def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['post_pk'] = self.kwargs['pk'] return context def form_valid(self, form): post_pk = self.kwargs['pk'] self.object = form.save(commit=False) self.object.target = … -
Django 2.0 url() to path()
I am currently learning Django. Until now I was working with Django 1.1 but now I am working with Django 2.0. Django 2.0 uses path() instead of url() and I don't quiet understand that. In Django 1.1 my urls looked like this: url(r'^about/$', views.AboutView.as_view(), name='about'), Now with Django 2 it looks like this path('about/', views.AboutView.as_view(), name='about'), So far so good but I just don't undertand how I can convert this url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(), name='post_detail'), So that it works with the new version. Just chagning url to path doesn't work, and changing url to re_path doesn't work either. Can someone help me with that Problem? Thanks in advance -
"AttributeError: 'psycopg2' has no attribute '__version__'" when switching from sqlite to postgres with Django - Vagrant
I'm a newbie in Django/Python. I just setup Django successfully with vagrant on my computer. But I want to change the default database from sqlite to postgresql. To do so, I just changed the database part on the setting.py file to : # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.path.join(BASE_DIR, 'db.postgresql'), } } Now whenever I run the command python manage.py runserver 0.0.0.0:8080 (which used to work well), I get the following error : Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fb91ed95ea0> Traceback (most recent call last): File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/ubuntu/.virtualenvs/meshine_api/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module …