Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and Dropzone.js methodology, creating an instance with images
I have 2 models Listing and Image, where a listing can have multiple images. class Listing(models.Model): title = models.CharField(max_length=100, blank=False) class ListingImage(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name='images') image = models.ImageField(blank=True) Ideally, I wanted to create such listings on a single page e.g. fill in all form information AND add images on the same page. It seems that this is not possible (if it's please let me know, but note that dropzone.js is Ajax) to handle 2 forms with a single view and I have made the following workarounds: Create listings first, add 2nd step to add listings to created model Create a placeholder listing, add images to it (via Ajax) and on form submit, change the placeholder information. Which method is better? views.py def add_image(request): # process images: problem we have no listing_instance to add them to if request.method == 'POST': form = ListingImageForm(request.POST, request.FILES) if form.is_valid(): ListingImage.objects.create(pk=None, listing=listing_instance) return HttpResponse( json.dumps({ "result": True, }), content_type="application/json" ) I'm looking for methodology advice. For example, to create a listing with images, do I need to first create the listing and then add images (2 steps) or add images first and listing information? My problem is that if I do that, the … -
django-modeltranslation causes django unable to access database
I have a django rest framework project already going with some models already created, and I am trying to add django-modeltranslation to the project. I followed the process as specified in django-modeltranslation documentation, but applications stop working after making migrations with django-modeltranslation modifications. Everytime I try to access de database, wether through the admin page or the django rest framework page, I get an error with the applications I have added transalation.py field. Applications without it continue working. This is my model: class Country(models.Model): name = models.CharField(max_length=40, unique=True, verbose_name=_('Name')) code = models.CharField(max_length=5, verbose_name=_('Code')) calling_code = models.CharField(max_length=3, null=True, blank=True, verbose_name=_('Calling code')) class Meta: verbose_name = _('Country') verbose_name_plural = _('Countries') def __str__(self): return self.name This is my translation.py @register(models.Country) class CountryTranslationOptions(TranslationOptions): fields = ('name',) And this is the error I get: TypeError at /es/general/countries/ _clone() got an unexpected keyword argument '_rewrite' I would appreciate any help. -
Django fails to persist locale changes
I'm using django 2.0.6 with pipenv 9.0.3 and virtualenv 15.1.0. I've been following the django's documentation on translation and it mostly seems to work, except that I can't change the language. If I change the settings.LANGUAGE_CODE directly, everything works, but when I try to select a per-user locale using the django.middleware.locale.LocaleMiddleware middleware, it always fails to change the language. No matter what I do, the {% get_current_language %} template tag always returns the language set in settings.LANGUAGE_CODE. When I print the ways django discover language preference, they are all correct or empty, except the settings.LANGUAGUE_CODE, yet the selected language is always the one set in settings.LANGUAGUE_CODE. print("SESSION LANGUAGE", request.session[translation.LANGUAGE_SESSION_KEY]) print("COOKIE", request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)) print("Accept-Language HEADER", request.META.get('Accept-Language')) print("Request Language Code", request.LANGUAGE_CODE) print("Request Language Code", settings.LANGUAGE_CODE) Things I tried: Changing the <html lang="en"> to the desired language. Calling translation.activate(language) (imported from django.utils import translation) in a view. Setting the language in the request's session in a view: request.session[translation.LANGUAGE_SESSION_KEY] = language Doing both previous steps together in a view. Using the built-in set language redirect view. I copied and pasted the form shown in the docs, and I added path('i18n/', include('django.conf.urls.i18n')), to the urls.py file that resides in the same directory as the settings.py file. … -
Convert django/python dict via json to javascript dict
I am trying to convert a python dict to a Javascript dict. As far as I understood I have to convert the python dict to Json, which I can convert to a Javascript Object view.py jsonheaderdict = json.dumps ( headerdict) {{jsonheaderdict}} in template results in {"F 1": ["BBBB", "AAAAA"], "F 2": ["ASDASD"], "F 3": ["QWEQWE"]} and my js looks like this $(".dict").click(function () { alert("first alert"); var result = JSON.parse(jsonheaderdict); alert(result); }); The first alert shows, the second one doesn't. What am i missing? Already tried var result = jQuery.parseJSON(jsonheaderdict); which didnt work either. I searched for similar question but didnt find any soultion that worked for me. EDIT For a better understanding how jsonheaderdict is created in my view: headerdict = dict() for d in projectdescriptors: #list of objects called descriptors dp = projectprojections.filter(descriptor=d) #list of objects connected to descriptors parray = [] for p in dp: parray.append(p.name) headerdict[d.name] = parray -
Is there an AudioField in Django2?
I really want to add an audio file to the database but theres no field for it. I know there's a github repository on it but it's very outdated so I don't think it will work in Django2. Is there any workaround for this? -
get dictionary value by key in django template
I have a dictionary like this : myDict = {key1:item1, key2:item2} how can I get item1 by providing key1 in django template and more if I have a nested dict like myDict2 = {key1:{key11:item11, key12:item12}, key2:{key21:item21, key22:item22}} for example how can I get item22 using key22 I know {{ myDict[key1] }} doesn't work -
Django : DiscoverRunner overriding raise error
I'm currently trying to define an other test_runner. To do so, i changed my settings.py : TEST_RUNNER = 'test_runner.MezzoTestsRunner' Here is my MezzoTestsRunner class : class MezzoTestsRunner(DiscoverRunner): def __init__(self): super(MezzoTestsRunner,self).__init__(keepdb=True) Then I used command : python manage.py test File "manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv super(Command, self).run_from_argv(argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/test.py", line 74, in execute super(Command, self).execute(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/test.py", line 89, in handle test_runner = TestRunner(**options) TypeError: __init__() got an unexpected keyword argument 'verbosity' I'm really suprised to have this result.. Does someone have already had the same ? Thank you :) PS : I'm using django 1.9 -
save() got multiple values for keyword argument 'max_length'
I'm using the save method of django, and I have the error of save() got multiple values for keyword argument 'max_length' This is my model: def generate_path(instance, filename): section=instance.document_title.historical_set.last().id_section year=str(section.year.number) course=(section.course.name) section=str(section.number) curso=curso.encode('utf-8').decode('utf-8') return os.path.join(ciclo,curso,seccion,filename) class UseExistingStorage(FileSystemStorage): def save(name, content, max_length=None): if not self.exists(name): return super().save(self,name, content, max_length) return name class Field(models.Model): type=models.CharField(max_length=50, choices=document_type, default=None) document_title=models.ForeignKey(Document,on_delete=models.CASCADE,null=True) file = models.FileField(null=True,blank=True, upload_to=generate_path,storage=UseExistingStorage()) rubric=models.FileField(null=True,blank=True,upload_to=generate_path,storage=UseExistingStorage()) and this is how I save the field: if FieldForm.is_valid(): course=request.POST.get('course') coursename=Course.objects.values('name').get(name=course) try: field.file=request.FILES['file'] except: pass try: field.rubric=request.FILES['rubric'] except: pass if type.find('a')!=-1: field.type='a' elif coursename.find('b')!=-1 : field.type='b' elif type.find('c')!=-1: field.type='c' else: field.type='d' field.document_title=documentTitle field.save() In generate path, I do the path to save the document in year/course/section and in the storage check if the field exist in that location.But I don't knoow why I'm getting that error -
how to display images by using django-tables2
I am new to Django-tables2, and I've searched around for this but haven't had much luck so looking for a bit of help. I am trying to display images in the cells of django-tables2; however, I only have the links to the images on my page and need to click the links and open new tabs to see the images. Here's what my code looks like now: models.py class Item(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True) collection = models.ManyToManyField(Collection) url = models.URLField(max_length=200, null=True) date = models.DateField('Date Added', default=datetime.date.today) item = models.ImageField(upload_to='media/img', null=True) class Meta: ordering = ["title", "date"] def __str__(self): return self.title tables.py class ImageColumn(tables.Column): def render(self, value): return mark_safe('<img src="/media/img/%s" />' % escape(value)) class ItemTable(tables.Table): image = ImageColumn('item') class Meta: model = Item fields = ('id', 'item', 'title', 'author', 'collection', 'tag', 'date') template_name = 'django_tables2/bootstrap.html' And on my webpage, it shows like this: enter image description here It seems the image column doesn't do any help, but I have no clue how to do it. Any help is much appreciated. -
Not getting the value of a form in Django
I have a form in Django, and I want to input something, and receive this data in the views.py from my project. I only have 1 function in the views.py so I guess my main problem is that I should have 2. But I am not really sure how to solve it, however have I tried. My form is this one, although with a simple form that can send data will work: <html> <head> <title> Practica django </title> </head> <form method="POST" action="" id = "loginForm"> {% csrf_token %} <input type="text" name="text" id= "text" value= '{% if submitbutton == "Submit" %} {{ firstname }} {% endif %}' maxlength="100"/> <input type="reset" name="Reset" id = "Reset" value="Reset" /> <input type="Submit" name="Submit" id = "Submit" value="Submit" /> {% if submitbutton == "Submit" %} <h1 id = 4 name="resultado2"> {{ type }}</h1> {% endif %} </form> </html> In my views I have this: def vistaFormulario(request,): text = request.POST.get('text') submitbutton = request.POST.get('Submit') m=str(text) print(m) print(text) context = {'text': text, 'submitbutton': submitbutton, 'type':q1} return render(request, 'form/form.html', context) As you can see, I have 2 prints, just to see what values do those values have. They have None before typing something and pressing the input button, and after … -
Making Sentry report error in multi-thread environment
I am using Sentry to power up exception handling logging in my app. The issue arises in the following code snippet: @api_view(['POST']) def testView(request): TestThread().start() return f_response_ok() class TestThread(threading.Thread): def __init__(self, *args, **kwargs): super(TestThread, self).__init__(*args, **kwargs) def run(self): print('Test') a = 1/0 # error is not reported in Sentry return True Is it possible to make Sentry report errors that have occurred in parallel thread? -
Django: "Model2.user" must be a "User" instance
I have the bellow models: class Model1(models.Model): Field1 = models.CharField(max_length=200) class Model2(models.Model) Field2 = models.ForeignKey(Model1, on_delete=models.CASCADE) Field3 = models.ForeignKey(User, on_delete=models.CASCADE) Email = models.EmailField(null=TRUE) And here's my forms.py: class Model1Form(ModelForm): class Meta: model = Model1 fields = ['Field1'] class Model2Form(ModelForm): class Meta: model = Model2 fields = ['email'] Model2Field2Formset = inlineformset_factory(Model1, Model2, form=Model2Form, extra=1) Model2Field3Formset = inlineformset_factory(User, Model2, form=Model2Form, extra=1) And here's my views.py: class NewEntry(CreateView): model = Model1 fields = ['Field1'] success_url = reverse_lazy('voting:index') def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['model2_field2'] = Model2Field2Formset(self.request.POST) data['model2_field3'] = Model2Field3Formset(self.request.POST, self.request.user) else: data['model2_field2'] = Model2Field2Formset() data['model2_field3'] = Model2Field3Formset() return data def form_valid(self, form): context = self.get_context_data() model2_field2 = context['model2_field2'] model2_field3 = context['model2_field3'] with transaction.atomic(): self.object = form.save() if model2_field2.is_valid() and model2_field3.is_valid(): model2_field2.instance = self.object model2_field2.save() model2_field3.instance = self.object model2_field3.save() return super().form_valid(form) I'm trying to create an entry for Model1, Field1. Then, using inlineformset_factory, create multiple email entries in Model2 that each one is associated with the same Field1_id entry and the respective user_id of each email in the form. But I'm getting a "Model2.user" must be a "User" instance. error on the model2_field3.save() line of code. If I comment out that line there are no errors and the entries are saved as … -
Django admin ManyToManyField filter by type for same table
I had Two table name Reservation Services In service table i am storing two type of data Service Addon Service Models.py class services(models.Model): Service_type_CHOICES = ( (1, 'Service'), (2, 'Addon'), ) service_id=models.IntegerField(primary_key=True) title=models.CharField(max_length=200) description=models.TextField() type=models.PositiveSmallIntegerField(choices=Service_type_CHOICES,) def __str__(self): return self.title Reservation Table class reservations(models.Model): user_id=models.IntegerField() arrival=models.DateTimeField() services_id=models.ManyToManyField(services, related_name='services') addons_id=models.ManyToManyField(services, related_name='addons') Now in my admin it is showing like below screenshot Currently it is showing all the services under both the feilds. i want to filter it by type. how can i achieve this in Django admin. I want to display service type 1 in first place. i.e cat1 and cat2 and on addons id i want to show type 2 services only. i.e Addon1 and Addon2 -
Issue Installing misaka in a django project i'm workin on
i'm pretty noob in django, been learning a bit of python, but right now i'm working on a social network project to apply what i've been learning, i need to install misaka, but when i use pip install misaka i get an error that reads: Command "python setup.py egg_info" failed with error code 1 in C:\Users\JHONAT~1\AppData\Local\Temp\pip-build-utm0mant\misaka\ and i dont really know what to do to solve it, i've tried using pip3 instead, no change and using pip2 also, i'm currently using python 3.6.4 and django 1.11 -
Serialize Many to Many Relationship with Extra fields
Please I'm stuck trying to get around this issue. Guess there is something I'm not getting after looking at other similar questions. I have these models: class Dish(BaseModel): class Meta: verbose_name_plural = 'dishes' name = models.CharField(_('dish'), max_length=100) dish_type = models.CharField(_("dish type"), max_length=100) price = models.PositiveIntegerField(_("price")) def __str__(self): return f"{self.name} costs {self.price}" class Order(BaseModel): dishes = models.ManyToManyField(Dish, through='DishOrder') customer = models.ForeignKey(Customer, on_delete=models.CASCADE) discount = models.PositiveIntegerField(_("total discount"), blank=True) total = models.PositiveIntegerField(_("total"), blank=True) shipping = models.PositiveIntegerField(_("shipping cost"), blank=True) grand_total = models.PositiveIntegerField(_("grand total"), blank=True) country = models.CharField(_('country code'), max_length=2) def __str__(self): return f"order from {self.customer} at {self.total}" def get_absolute_url(self): return reverse('order-details', kwargs={'pk': self.pk}) class DishOrder(models.Model): dish = models.ForeignKey(Dish, on_delete=models.CASCADE, related_name='dishes') order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='dishes') quantity = models.PositiveIntegerField(_("quantity")) discount = models.PositiveIntegerField(_("discount")) price = models.PositiveIntegerField(_('price')) And the corresponding serializers like so: class DishOrderSerializer(serializers.ModelSerializer): class Meta: model = DishOrder fields = ( "quantity", "discount", "price" ) class OrderSerializer(serializers.ModelSerializer): dishes = DishOrderSerializer(source='dish', many=True) class Meta: model = Order fields = ( "id", "country", "customer", "delivery_address", "payment_method", "vendor", "dishes", "total", "shipping", "discount", "grand_total", "voucher", "status" ) So as can be seen, I have a m2m relationship via a through table. However I can't get the serializer to work. This is the error I keep getting: Got AttributeError when … -
How can I change default database in Django?
I am not able to change my default database SQLite to PostgreSQL.Please Help -
Do a simple query with Django Models
I have this model from django.db import models from django.utils import timezone class Data(models.Model): palabra = models.CharField(max_length=200) cantidad = models.IntegerField() fecha = models.DateTimeField( default=timezone.now) def returnFecha(self): return self.fecha def __str__(self): return self.palabra , self.cantidad , self.fecha And I am trying to get a value of the table (for example, one "cantidad", BUT ONLY ONE (even if there are repeated values)). Having into account that I have already filled the table/db with data, I have tried this: q1=Data.objects.get(cantidad=56).first() But this gets me this error: get() returned more than one Data -- it returned 7! Why? I wrote "first()" so there should not be any problems. -
How to transfer page_number to urls.py
I want transfer page_number to url with name='onePart' from part_list.html. In my code page_number=1, but I want change it to current page of paginator depends on page. How I can do this? P.S. sorry for my english:) views.py: def PartyNumView(request, page_number = 1): all_parties = Part.objects.all() current_page = Paginator(all_parties, 1) try: context = current_page.page(page_number) except PageNotAnInteger: context = current_page.page(1) except EmptyPage: context = current_page.page(current_page.num_pages) return render_to_response('part_list.html', {'PartyNum': context}) def forOne(request, pk): onePart = get_object_or_404(Part, pk=pk) return render_to_response('SinglePart.html', {'onePart': onePart}) **urls.py:** urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^parties/(\d+)/$', PartyNumView), url(r'^parties', PartyNumView), url(r'parties/(?P<page_number>[\d]+)/(?P<pk>[\d]+)$', forOne, name='onePart'), url(r'^main/', TemplateView.as_view(template_name='main.html')), #static html url(r'^measures/', TemplateView.as_view(template_name='IcDesc.html')), #static html ] A little bit of HTML code part_list.html: {% for object in PartyNum %} <tr> <td>{{ forloop.counter }}</td> <td><a href="{% url 'onePart' pk=object.pk page_number=1%}"> {{ object.Party_number }}</a></td> <td>{{ object.Film }}</td> <td>{{ object.Thick }}</td> <td>{{ object.Critical_temperature }}</td> <td>{{ object.R_s }}</td> {% endfor %} </tbody> </table> </table> <div class="row" style="margin:auto"> <div class="large-3 large-offset-5 columns"> <ul class="pagination"> {% if PartyNum.has_previous %} <li class="arrow"><a href="/parties/{{ PartyNum.previous_page_number }}/">&laquo;</a></li> {% else %} <li class="arrow disabled"><a href="">&laquo;</a></li> {% endif %} {% for page in PartyNum.paginator.page_range %} {% if page == PartyNum.number %} <li class="current"><a href="/parties/{{ page }}/">{{ page }}</a></li> {% else %} <li><a href="/parties/{{ page }}/">{{ page … -
django mongodb _id issue
I'm using MongoDB and Djongo. I've imported an existing MongoDB with mongorestore and I can list all db content in a Django template. What I want to do: make links to the detail view for each document displayed in the list. I've followed the suggestions in this post trying just to print the MongoDB _id value but get the error: string indices must be integers These are my files: Template elenco_strutture.html {% load strutture_ricettive_tags %} {% block content %} {% for struttura in strutture %} <div class="post"> <div class="date"> {{ struttura.loc }} </div> <h1>Mongo ID: {{ object|mongo_id }}</h1> <br>coord: {{ struttura.location|linebreaksbr }} </div> {% endfor %} {% endblock %} strutture_ricettive_tags.py from django import template register = template.Library() @register.filter("mongo_id") def mongo_id(value): return str(value['_id']) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.elenco_strutture, name='elenco_strutture'), url(r'^struttura/(?P<mongo_id>[0-9]+)/$', views.struttura_detail, name='struttura_detail'), ] views.py from django.shortcuts import render, get_object_or_404 # Create your views here. from .models import Strutture def elenco_strutture(request): strutture = Strutture.objects.all() return render(request, 'strutture_ricettive/elenco_strutture.html', {'strutture': strutture}) def struttura_detail(request, _id): struttura = get_object_or_404(Struttura, mongo_id=mongo_id) return render(request, 'strutture_ricettive/struttura_detail.html', {'struttura': struttura}) -
inserting in sqlite with django forms
i have used forms to insert my data in sqlite, it worked several times, i found that it stopped inserting with form, i changed something in it but i have removed this change, so i don't know why it don't work : views.py def add_story(request): if request.method == "POST": form = StoryCreate(request.POST) if form.is_valid(): storyitem = form.save(commit=False) str = StoryDetails() str.Author = form.cleaned_data["Author"] str.story_content = form.cleaned_data["story_content"] str.LogoUrl = form.cleaned_data["LogoUrl"] str.storyNaMe = form.cleaned_data["storyNaMe"] str.save() storyitem.save() else: form = StoryCreate() return render(request, 'story_form.html', {'form':form}) models.py class StoryDetails(models.Model): Author = models.CharField(max_length=250) storyNaMe = models.CharField(max_length=250) LogoUrl = models.FileField(null=True) story_content = models.TextField(max_length=40000) def __str__(self): return self.storyNaMe html file {% extends 'base.html' %} {% block title %} New Story {% endblock %} {% block body %} <form method="POST" action=""> {% csrf_token %} {{ form }} <input type="submit" value="Save"> </form> {% endblock %} urls.py url(r'^', views.add_story, name='add'), url(r'^adding', views.list, name='lists'), url(r'^register', views.post, name='register'), -
Unusual error in Django. Cannot login into admin after creating superuser
This is a weird problem that I am facing in my Django application. Configuration : Python 3.6 Django 2.0.6 DB : Djongo (MongoDB connector : Djongo repository) I have overwritten the create_superuser to: def create_superuser(self, email, is_staff, password): user = self.model( email=email, is_staff=True, is_active=True, ) user.set_password(password) user.save(using=self._db) return user I am able to create the superuser successfully but I am not able to login into the admin page. Following is my traceback: Internal Server Error: /admin/login/ Traceback (most recent call last): File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 398, in login return LoginView.as_view(**defaults)(request) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/utils/decorators.py", line 62, in _wrapper return bound_func(*args, **kwargs) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/utils/decorators.py", line 58, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/utils/decorators.py", line 62, in _wrapper return bound_func(*args, **kwargs) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/fractaluser/dev_eugenie/venv_eugenie/lib/python3.6/site-packages/django/utils/decorators.py", line 58, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File … -
Joining multiple Django models
I have three Django models related by foreign key constraint and they all have data. How should I join all of them together and display the data in my template? (something similar to INNER JOIN in SQL). The view is, def seeAllData(request): template = loader.get_template('seeAllData.html') context = { 'From1' : Form1(), 'Form2' : Form2(), 'Form3' : Form3(), } return HttpResponse(template.render(context, request)) Also, when I try the above approach, I get some text fields in the form rather than the data. (I want to show the data in a grid format). Thanks in advance. -
How to create entry for intermediary table with inlineformset_factory
I have the bellow 2 models: class Model1(models.Model): Field1 = models.CharField(max_length=200) class Model2(models.Model) Field2 = models.ForeignKey(Model1, on_delete=models.CASCADE) Field3 = models.ForeignKey(User, on_delete=models.CASCADE) Email = models.EmailField(null=TRUE) The second model has two foreign keys, one to Model1 and the second to auth_user. I'm trying to use formsets and simultaneously create an entry for Model1 and multiple Email entries for Model2 that are associated to registered users and the single entry of 'Model1'. Something similar to this tutorial but my model has 2 parent model instead of one. I followed the above tutorial but couldn't make it work. Any ideas on how to proceed? -
download zip file with data from multiple models in csv format
I'm using Django 2.0 I have to download data from multiple models in csv format zipped in a zip file. I'm using django-import-export plugin to generate csv file for the model data What I'm doing is def download_all_data(request): # user data user_resource = UserResource() queryset = User.objects.filter(username=request.user) data_set = user_resource.export(queryset) # favourite arbitrase favourite_arbitrase_resource = FavouriteArbitraseResource() favourite_arbitrase_queryset = FavouriteArbitrase.objects.filter(user=request.user) data_set_favourite_arbitrase = favourite_arbitrase_resource.export(favourite_arbitrase_queryset) response_user_data = HttpResponse(data_set.csv, content_type='text/csv') response_user_data['Content-Disposition'] = 'attachment; filename="user_data.csv"' response_favourite_arbitrase = HttpResponse(data_set_favourite_arbitrase.csv, content_type='text/csv') response_favourite_arbitrase['Content-Disposition'] = 'attachment; filename="favourite_arbitrase_data.csv"' zipped_file = io.BytesIO() with zipfile.ZipFile(zipped_file, 'w') as zip_file: zip_file.writestr('text/csv', response_user_data) zip_file.writestr('text/csv', response_favourite_arbitrase) zip_response = HttpResponse(zipped_file, content_type='application/octet-stream') zip_response['Content-Disposition'] = 'attachment; filename=my_file.zip' return zip_response This is giving error object of type 'HttpResponse' has no len() -
Unable to limit size of string in django template
I try to use the slice or the truncatechars tags in my django (1.6.11) template as following: <p class="abstract">{{ item.abstract | slice:":5" }}</p> <p class="abstract">{{ item.abstract | truncatechars:5 }}</p> But I get the following error in the webdeveloper tool: assets.min.js:11 Error: [$injector:unpr] Unknown provider: truncatecharsFilterProvider <- truncatecharsFilter