Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python3 + Django . Cyrillic text unicode error
Please help with typical problem but still not clear how to solve. Using python 3.4 + django 1.8. Ajax function sends text as key for search to django, but when it's cyrrylic text the whole thing doesn't work. No error is shown. As far as I understand it's up to python3 handling unicode 'features'. Print function prints correct text to the console, when it's cyrillic output of relevant event objects is just empty(but there must be results for sure) @api_view(['POST', ]) def live_search(request): if request.method == 'POST': key = request.data['key'] result = Event.objects.filter(title__istartswith=key) events = serializers.serialize('json', result) print (key) print (result) data = { 'events': events, } return Response(data) How to fix it? -
Photo archive: choosing the tool
Django 1.11 Python 3.6.1 I'm building a photo archive. Users will upload jpg, png, tiff. Photos will usually be scanned in high resolution. So, the files will be big. My plan is: Check whether it is really an image file. Create a directory (I'll generate unique names based on IDs). Keep what a user has upload. The best quality: just for downloading, not for showing online. Generate 3 web optimized images: for Bootstrap's .col-sm-, .col-md-, .col-lg- classes. Such images will be used in srcset attribute on the . As these Bootstrap's classes have container widths 750px, 970px and 1170px respectively, I'm going to organize widths of generated images, say, 700, 900, 1120 px. Generate a small icon. Just as a preview. As I lack experience, could you just give me some pieces of advice here: Whether this idea is generally ok. Maybe some corrections? What instrument should I use for this? There is django-imagekit seemingly suitable for this. Or should I use Celery or something. Maybe some comment on what to pay attention to. This is a very general question: when I choose the strategy, I'll be able to read something and ask more refined questions. The main question is … -
Check valid url before reporting 405 for detail view in Django REST framework
I have a ViewSet that looks like this: class BoardViewSet(viewsets.GenericViewSet, ...): @detail_route(methods=["post"]) def register(self, request, pk): board = self.get_object() ... I get the following results, when I make these requests: POST /board/1234/register -> 200 POST /board/BEEF/register -> 404 NOT FOUND GET /board/1234/register -> 405 NOT ALLOWED GET /board/BEEF/register -> 405 NOT ALLOWED It's the last item in the list that concerns me. Performing a GET request on an invalid URL returns the NOT ALLOWED response, not the NOT FOUND response, even though that's an invalid URL. I understand why this happens, in terms of how Django and the DRF's routing works. My question is twofold: Is this the appropriate behavior, in terms of HTTP response code semantics? If not, is there a (good) way to fix this? -
Can I use drf-haystack with django-haystack?
I've already had my Django-Haystack application with SOLR working. I want to build an Django Rest framework API for my application. By doing some research, I found the library drf-haystack. I followed the steps on the Basic Use example on its documentation But it seems it doesn't work with my current existing Django-Haystack application. I got error about "A server error occurred. Please contact the administration." Here are some details about my code. I have a model called Resource: class Resource(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=30) For my Django-Haystack app, I have my index class: class ResourceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr="title") author = indexes.CharField(model_attr="author") For my drf-haystack, I have the following serializer and api view class: class ResourceSerializer(HaystackSerializer): class Meta: index_classes = [ResourceIndex] fields = [ "text", "title", "author" ] class ResourceAPIView(HaystackViewSet): index_models = [Resource] serializer_class = ResourceSerializer In my urls.py, I have router = routers.DefaultRouter() router.register("resource", ResourceAPIView, base_name="resource-api") urlpatterns = patterns("", url(r'^', include(router.urls)), url(r'^search/$', MyView.as_view(), name='haystack_search')) BTW, I am using Django-Haystack 2.5.0 with SOLR and drf-haystack 1.6.1 Does anyone have any idea? -
Serialize the creation of user and profile django rest framework
I'm trying to create an user and his profile through DRF, but I don't find the correct way to do it. Here's my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) language = models.CharField(max_length=4, default='es') def __unicode__(self): return "%s - %s" % (self.user, self.language) my serializers.py class UserSerializer(serializers.ModelSerializer): def create (self, validated_data): user = get_user_model().objects.create(username=validated_data['username']) user.set_password(User.objects.make_random_password()) user.save() return user class Meta: model = get_user_model() fields = [ 'username', ] class ProfileCreateSerializer(serializers.ModelSerializer): username = UserSerializer() class Meta: model = Profile fields = [ 'username', 'language', ] my views.py class ProfileCreateAPIView(CreateAPIView): model = Profile serializer_class = ProfileCreateSerializer if I try to create it shows me this error: The `.create()` method does not support writable nestedfields by default. Write an explicit `.create()` method for serializer `api.serializers.ProfileCreateSerializer`, or set `read_only=True` on nested serializer fields. I've tried adding read_only=true but doesn't show me an option to create an username and also many=True but only shows me the users already created (doesn't let me create one) I'm using django 1.9.1 and django rest framework 3.3.2 -
How to query using a different field other than the PK (primary key) field in DetailView
url.py urlpatterns = [ url(r'^employee/(?P<emp_no>[0-9]+)/$', TitleDetail.as_view(), name='e-title'), # /employee/10001/ ] views.py class TitleDetail(DetailView): model = Title pk_url_kwarg = "emp_no" def get_context_data(self, **kwargs): context = super(TitleDetail, self).get_context_data(**kwargs) context['title_list'] = Title.objects.filter(emp_no_id=self.kwargs['emp_no']) return context models.py class Title(models.Model): emp_no = models.ForeignKey(Employee) title = models.CharField(max_length=50) from_date = models.DateField() to_date = models.DateField() # sample data in database: id title from_date to_date emp_no_id ---------- --------------- ---------- ---------- ---------- 1 Senior Engineer 1986-06-26 9999-01-01 10001 2 Staff 1996-08-03 9999-01-01 10002 why does it give me a "PAGE NOT FOUND: No title found matching the query." -
Celery-beat: why it doesn't work in Django?
Task itself works well(run asynchronously), but when I trying using celery beat it does't work. I followed http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#beat-custom-schedulers. This is my django project structure: . . ├── clien │ ├── __init__.py │ ├── admin.py │ ├── management │ │ ├── __init__.py │ │ └── commands │ │ ├── __init__.py │ │ └── crawl_clien.py │ ├── migrations │ ├── models.py │ ├── tasks │ │ ├── __init__.py ## ==> code │ │ └── crawl_clien_task.py ## ==> code │ ├── templates │ ├── urls.py │ └── views ├── config │ ├── __init__.py ## ==> code │ ├── celery.py ## ==> code │ ├── settings │ │ ├── __init__.py │ │ ├── partials │ │ │ ├── __init__.py │ │ │ ├── base.py │ ├── urls.py │ └── wsgi.py ├── manage.py . . Only clien is registered in app. Here are the codes: config/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab app = Celery('chois_crawler') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'my_task': { 'task': 'tasks.crawl_clien_task', 'schedule': crontab(minute='*/1'), }, } config/__init__.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] clien/tasks/crawl_clien_task.py from __future__ import absolute_import, unicode_literals from celery import shared_task, Celery from … -
Forms Not Appearing
I'm following the following tutorial to learn how to create a Django form. I'm really stuck on why the form isn't appearing on the designated html page. Here's my code: Forms.py class ReviewForm(ModelForm): class Meta: model = Review fields = ('user_name', 'rating', 'content') widgets = { 'content': Textarea(attrs={'cols': 40, 'rows': 15}) } Views.py: def add_review(request, wine_id): wine = get_object_or_404(Wine, pk=wine_id) form = ReviewForm(request.POST) if form.is_valid(): # Retrieves values entered rating = form.cleaned_data['rating'] content = form.cleaned_data['content'] user_name = form.cleaned_data['user_name'] review = Review() review.wine = wine review.user_name = user_name review.rating = rating review.content = content review.pub_date = datetime.datetime.now() review.save() return HttpResponseRedirect(reverse('reviews:wine_detail', args=(wine.id,))) return render(request, 'reviews:/wine_detail.html', {'wine': wine, 'form': form}) Template <form action="{% url 'reviews:add_review' wine.id %}" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Add" /> </form> I don't believe there's any syntax error on any one of these. I have a hunch that the form that's being passed as an argument in the add_review function is incorrect. But, I'm not sure how to validate it, let alone correct it. Any help would be much appreciated. -
Dropzone with django image upload
Im trying to upload images using Dropzone.js . There doesnt seem to be any current tutorials for Dropzone although i used this link: https://amatellanes.wordpress.com/2013/11/05/dropzonejs-django-how-to-build-a-file-upload-form/ Essentially what i want to do is , The user uploads multiple images . a hotel_id is attached to the images and stored in the hotelphotos table as a url which is unique each time . MY code Models.py class Photo(models.Model): hotel = models.ForeignKey(Hotels,on_delete=models.CASCADE) path = models.FileField(upload_to='files/%Y/%M/%d) forms.py class PhotosForm(forms.ModelForm): class Meta: model = Photo fields = ['path'] views.py def uploadPhoto(request,hotelid): if request.method == 'POST': form = PhotosForm(request.POST,request.FILES) if form.is_valid(): new_file = Photo(path = request.FILEs['file'] , hotel_id = hotelid) new_file.save() else: form = PhotosForm() hotelid = pk data = {'form': form, 'hotelid':hotelid} return render(request, template , data) The form <form class="dropzone action="{% url 'ManageHotels:uploadPhoto' hotelid %} method = "POST"> </form> Files uploaded dont get created and the url also doesnt add to the database. Hope someone can help! -
Django migrations: TypeError: db_type() takes exactly 1 argument (2 given)
So I am trying to integrate my legacy postgresql to django. I have successfully created my models following this: https://docs.djangoproject.com/en/1.11/howto/legacy-databases/ However when I add something to my models and try to migrate I get the following error: Operations to perform: Apply all migrations: admin, auth, contenttypes, pSQL, sessions Running migrations: Applying pSQL.0001_initial...Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Library/Python/2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/Library/Python/2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Library/Python/2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Library/Python/2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/Library/Python/2.7/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Library/Python/2.7/site-packages/django/db/migrations/operations/models.py", line 96, in database_forwards schema_editor.create_model(model) File "/Library/Python/2.7/site-packages/django/db/backends/base/schema.py", line 246, in create_model definition, extra_params = self.column_sql(model, field) File "/Library/Python/2.7/site-packages/django/db/backends/base/schema.py", line 136, in column_sql db_params = field.db_parameters(connection=self.connection) File "/Library/Python/2.7/site-packages/django/db/models/fields/init.py", line 647, in db_parameters type_string = self.db_type(connection) TypeError: db_type() takes exactly 1 argument (2 given) -
postgres does not start. (involves Django and Docker)
I do postgres -D /path/to/data I get 2017-05-01 16:53:36 CDT LOG: could not bind IPv6 socket: No error 2017-05-01 16:53:36 CDT HINT: Is another postmaster already running on port 5432? If not, wait a few seconds and retry. 2017-05-01 16:53:36 CDT LOG: could not bind IPv4 socket: No error 2017-05-01 16:53:36 CDT HINT: Is another postmaster already running on port 5432? If not, wait a few seconds and retry. 2017-05-01 16:53:36 CDT WARNING: could not create listen socket for "*" 2017-05-01 16:53:36 CDT FATAL: could not create any TCP/IP sockets Can someone help me figure out what is going wrong? When I do psql -U postgres -h localhost it works just fine. Though I need to start postgres to get it running on Docker and Django Please help Thanks in advance -
Django(/JS?) displaying and deleting uploaded media files on site
I currently have a page where users can access their old uploaded files and these are filtered by account using os.walk(). The download links are currently functional, but the link text is just the media file's URL. I would ultimately like to allow the user to delete their old files as well, checkbox and one delete button style - I'm unsure how to implement file deletion and have it so each checkbox "remembers" what file to delete. Are there any Javascript plugins that would take care of display, download, and deletion while not giving access to other users' folders? I'm also unsure how to pass files into the html, for now I've been passing the relative URL but I feel like there should be a cleaner way to do it. -
Iframe is empty in Firefox but works fine in Chrome
I have a django app that I'm trying to embed on a page with a different domain. Let's say my django app is hosted at https://myapp.io, and the page I'm trying to embed it in is at example.com. Here's what my iframe looks like: <iframe src="https://myapp.io" style="border: medium none; min-height: 350px; overflow: hidden;" id="myIframe" scrolling="no"></iframe> Here is the actual request+response that is sent when the iframe loads in Chrome. This matches exactly the request that is sent in Firefox. The X-FRAME-OPTIONS was set to ALLOW-FROM myapp.io. The Request headers that were left out were: Host:myapp.io Referer:https://example.com/path/to/current/page Upgrade-Insecure-Requests:1 This request works in Chrome and the contents of the iframe display correctly. However, in Firefox, the iframe is empty. In Firefox, I can replace my myapp.io URL with https://w3schools.com, the contents of w3schools.com displays in the iframe. How do I fix this and allow Firefox to display my Iframe? -
default shipping method in django-oscar
I am trying to write a shipping method base on both by country and also weight-base in django-oscar. It seems the default shipping methods must also have these from oscar.apps.shipping.methods import Free, FixedPrice, NoShippingRequired I do not required any of the above and would only provide discount for shipping through discounts. How do I write by repository.py so I do not apply any of these oscar.apps.shipping.methods import Free, FixedPrice, NoShippingRequired so I can just write my class Repository(CoreRepository): without writing methods += [NoShippingRequired()] methods += [FixedPrice()] methods += [Free()] I really just need to write the repository.py base on country and weight-base. No free, or FixedPrice or NoShippingRequired. Basically because shipping cost would be different for each customer. Please, help. -
How do implement Chart.js with my view? Django
The user can select what two aircraft that they want to compare numeriaclly. They way I've coded the view is that the value calculated is appended into a row and that row is displayed in the template. My question is: How do I implement/return chart.js for each category (passengers, range, cost) and that it is displayed underneath each cateogry? Would I have to create several charts for each category? Any step in the right direction would be appreciated! def aircraft_delta(request): ids = [int(id) for id in request.GET.get('ids') if id != ','] print ("The ids are:", ids) aircraft_to_compare = Aircraft.objects.filter(id__in=ids) property_keys = ['image','name', 'engines', 'cost','maximum_range','passengers','maximum_altitude','cruising_speed', 'fuel_capacity','wing_span','length'] column_descriptions = { 'image': '', 'name': 'Aircraft', 'maximum_range': 'Range (NM)', 'passengers': 'Passengers', 'cruising_speed': 'Max Speed (kts)', 'fuel_capacity': 'Fuel Capacity', 'engines':'Engines', 'cost':'Cost', 'maximum_altitude':'Maximum Altitude', 'wing_span':'Wing Span (FT)', 'length':'Total Length (FT)' } data = [] for key in property_keys: row = [column_descriptions[key]] first_value = getattr(aircraft_to_compare[0], key) second_value = getattr(aircraft_to_compare[1], key) if key not in ['image', 'name', 'manufacturer','aircraft_type','body','description']: delta = abs(first_value - second_value) else: delta = '' row.append(first_value) row.append(delta) row.append(second_value) data.append(row) return render(request, 'aircraft/aircraft_delta.html', { 'data': data }) -
Sending Data to a remote Server
I need to Send Data/logs Saved by This Key-logger for a remote server-for analysis- How can I do this If the Server is written in Django? https://github.com/Xeroday/ChromeLogger -
Django uWSGI application is stalled
My Django Python 3 uWSGI application is stalled (does not accept requests) and uses 100% CPU power. How to find the error causing it to use 100% CPU and do nothing? I would like to see the stack trace. How? -
revoke celery chain eager mode
I am using celery chain in Django project. For chained tasks, I am using task_postrun signal to revoke all subsequent tasks similar to this. @task_postrun.connect def task_postrun_handler( signal, sender, task_id, task, retval, state, args, kwargs, **kwds ): # do other things first if retval != 1: task.request.chain[:] = [] So if the task's return value is not 1, then revoke all the subsequent tasks. It works fine. However, in my test, I run the tasks in eager mode. It does enter the task_postrun_handler, but doesn't have array of chain ( the callbacks is None as well). In this way, I am not able to terminate the task chains in my test. I tried both in celery 3.1.23 and celery 4.0.2 Thanks for any help. -
Django cannot serve uploaded media in production pythonanywhere
After succeed in development stage to serve the media uploaded (images) and view it in the pages, i am struggling in achieving this thing in production server and deployment seems too hard for me. using Pythoneverywhere platform i always get not found error: 2017-05-01 19:22:48,923 :Not Found: /media/I am title/31.jpeg not only for this particular image, for every image i upload. here is my settings file (some details are omitted not necessary here): import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DEBUG = False STATIC_URL = '/static/' # origin of permanent static files STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") # temporarly loc MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), #'/var/www/static/', ] Here is my wsgi file mport os from django.core.wsgi import get_wsgi_application from django.contrib.staticfiles.handlers import StaticFilesHandler os.environ.setdefault("DJANGO_SETTINGS_MODULE", "flog.settings") application = get_wsgi_application() application = StaticFilesHandler(application) It is just not working, I have tried to add this line ( Which is not recommended as in docs) static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Still doesn't solve the problem. However, when i navigate through the platform i can find the media uploaded at the targeted folder ! Its been 2 days i am just trying to deploy the … -
Sending email to selected users using django
I want to send mails for the only users whose batch and department is matching with that of request's batch and department.Batch and department are in OneToOne relation with the user.The mail should be send from this function.That is mail should be send when the boolean field is_principal is true.Here is my code. models.py class Rep(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) dept = models.ForeignKey(Departement, default=0) batch = models.ForeignKey(Batch, default=0) semester = models.ForeignKey(Semester, default=0) def __str__(self): return str(self.user) class Retest(models.Model): semester = models.ForeignKey(Semester) dept = models.ForeignKey(Departement) batch = models.ForeignKey(Batch) date = models.DateField(blank=True, null=True) subject = models.ForeignKey(Subject) name = models.CharField(max_length=50) admnno = models.CharField(max_length=50) reason = models.CharField(max_length=50) proof = models.CharField(max_length=200) is_hod = models.BooleanField(default=False) is_principal = models.BooleanField(default=False) notify = models.BooleanField(default=False) is_sure = models.BooleanField(default=False) def get_absolute_url(self): return reverse( 'retest:retestform') def __str__(self): return self.name views.py def accepted(request, retest_id): if request.method == 'POST': retest.is_principal = True retest.save(update_fields=['is_principal']) email = EmailMessage('RMS', 'Your Notifications are Pending.', to=[.email]) email.send() return render(request, 'retest/request.html' , {'retest': retest}) How can I set the conditions for the to address? -
Show comments without refreshing
I want to show the comment user posts, right after he posts it.I already made the ajax upload the comment, how can i display it to the user, without refreshing? I have this ajax code: $(".comments input[name='post']").keydown(function (evt) { var keyCode = evt.which?evt.which:evt.keyCode; if (keyCode == 13) { var form = $(this).closest("form"); var container = $(this).closest(".comments"); var input = $(this); $.ajax({ url: "{% url 'comment' letnik_id=letnik_id classes_id=classes_id subject_id=subject_id %}", data: $(form).serialize(), type: 'post', cache: false, beforeSend: function () { $(input).val(""); $(input).blur(); }, success: function (data) { alert("Successful comment"); $(input).val(""); $(input).blur(); } }); } }); This posts the comment. In views.py i save comment: def comment(request, letnik_id, classes_id, subject_id): try: if request.method == 'POST': exam_id = request.POST.get('exam_id') exam = get_object_or_404(Exam, id=exam_id) comment = request.POST.get('post') comment = comment.strip() if len(comment) > 0: instance = ExamComment( exam=exam, comment=comment, comment_user=request.user) instance.save() return render(request, 'exam_comment.html', {'comment': comment}) html = '' for comment in exam.get_comments(): html = '{0}{1}'.format(html, render_to_string('exam_partial_comment.html', {'comment': comment})) return HttpResponse(html) else: return HttpResponseBadRequest() except Exception: return HttpResponseBadRequest() -
Can't get ChosenJS to work
I am trying to create a select box with an auto complete feature. I read that ChosenJS was the best solution out there for this. I loaded up the script and stylesheet for chosen, and verified they were successfully loaded (in the network tab of my web console). The element I am targeting with the .chosen jquery method is simply not working. the method is being called in a document.ready function, and I am console logging the element so I know it exists for chosen to grab, and do its thing with, but it just acts like a normal select box. Maybe its because I'm sick and my brain is functioning at half the capacity, and it's something obvious I'm not seeing, but can anyone see something I'm doing wrong ? The end of my base template "JQuery is loaded as well" <select class="chosen-select" style="width: 20%;"> <option value="Chandler">Chandler</option> <option value="Tempe">Tempe</option> <option value="Mesa">Mesa</option> <option value="Phoenix">Phoenix</option> </select> <script type="text/javascript" src="/static/js/chosen.jquery.js"></script> <link rel="stylesheet" href="/static/css/chosen.css"> <script> $(document).ready(function(){ $(".chosen-select").chosen(); }) </script> </body> -
Django: Create check boxes dynamically based on select dropdown with Jquery/Ajax?
I'm using Django Crispy Forms and in my creation form, I'd like my users to select one category in a select dropdown and then I want to fetch all features related to that category and display all the features in check boxes below. I figured ajax/Jquery makes sense for that, so I came up with the following: My View: def show_category_feature_set(request): category_id = request.GET.get('category') category = Category.objects.get(id=category_id) features = category.features.all().values('name', 'id') response_data = {} try: response_data['features'] = list(features) except: response_data['error'] = "Sorry, couldn\'t load any features" return JsonResponse(response_data) My Model: class Feature(models.Model): name = models.CharField(max_length=100, blank=False) class Category(models.Model): name = models.CharField(max_length=50, blank=False) slug = models.SlugField(unique=True) features = models.ManyToManyField(Feature, through='FeatureCategorization' ) class FeatureCategorization(models.Model): category = models.ForeignKey(Category) feature = models.ForeignKey(Feature) Here is my form: class ListingForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ListingForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'listing' self.helper.form_show_errors = True self.helper.form_method = 'post' self.helper.form_action = 'submit' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = Listing fields = ['title', 'event_types', 'category', 'features', 'description', 'blog_url', 'website', 'pricing_page'] widgets = { 'event_types': forms.CheckboxSelectMultiple(), 'features': forms.CheckboxSelectMultiple() } And here is the html that my Django Crispy Form (Model Form) generates. I need to create this block dynamically, so the checkboxes below need to be shown based … -
I get a NoReverseMatch at /reset/Mg/4lo-d6fc464827e39eceb093/
I am working on a django site for practice, and I've been trying to setup the built-in auth system. When I went to try it out I ran other some issues I can't figure out on the password_reset_confirm view. I keep getting a NoReverseMatch when I try to use it. my url conf is from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views from home import views as home_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', home_views.index, name="index"), url(r'^registration/$', home_views.registration, name="registration"), url(r'^login/$', auth_views.login, name="login"), url(r'^password_reset/$', auth_views.password_reset,{'template_name':'registration/password_reset.html'}, name='password_reset'), url(r'^password_reset/done/$', auth_views.password_reset_done,{'template_name':'registration/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm, {'template_name':'registration/reset.html'},name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete,{'template_name':'registration/reset_done.html'}, name='password_reset_complete'), url(r'^logout/$', auth_views.logout, {'next_page':'index'},name='logout'), ] Any assistance would be great, I am really stuck on this one. -
Django wrong encoding in admin interface
Wrong encoding in admin interface but I dont understand why. In project settings is set utf-8 My admin.py # -*- coding: utf-8 -*- from django.contrib import admin from main.models import file_record class FilesAdmin(admin.ModelAdmin): list_display = ['file_name', 'owner', 'date'] # Register your models here. admin.site.register(file_record, FilesAdmin)