Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to create view with list of objects and forms to update?
I'm trying to solve my problem with django for last 2 days, I've searched many reddit posts/ git repos / stack questions and I've achieved nothing. I'm learning django and doing a project to help me in my current job. My goal is to make detail view of model "Partner" where I'll list all it's "PartnerMugs" models.py class Partner(models.Model): partner_name = models.CharField(max_length=255) class Meta: ordering = ["partner_name"] def __str__(self): return self.partner_name def get_absolute_url(self): return reverse("partners:detail", kwargs={"pk":self.pk}) class PartnerMug(models.Model): partner = models.ForeignKey('Partner', on_delete=models.CASCADE) pattern = models.ForeignKey('patterns.Pattern', on_delete=models.CASCADE) xs_amount = models.IntegerField(default=0) xl_amount = models.IntegerField(default=0) class Meta: ordering = ["partner"] def __str__(self): return str(self.partner) + " " + str(self.pattern) def get_absolute_url(self): return reverse('partners:detail', args=[self.partner.pk]) The problem is that I have no idea how to put form for each "PartnerMug" object in my list. I tried to do something with inlineformset_factory, but I didn't find the way how to put it in my for loop. form.py class PartnerForm(forms.ModelForm): class Meta: model = Partner fields = ['partner_name'] class MugAmountForm(forms.ModelForm): class Meta: model = PartnerMug fields = ['xs_amount','xl_amount',] MugAmountFormSet = inlineformset_factory(Partner, PartnerMug, form=MugAmountForm, extra=0) For now my Class Based View looks like this(it's based on github repo): view.py class PartnerDetailView(ModelFormMixin, DetailView): model = Partner form_class = … -
Django - update or create obj must be an instance or subtype of type
I have an update or create method in my form valid function and im getting the error, when I submit the form. Im not sure as to why? super(type, obj): obj must be an instance or subtype of type Full trace: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/itapp/itapp/config/views.py" in device_details 151. form = DeviceSubnetForm(request.POST) File "/itapp/itapp/config/forms.py" in __init__ 135. super(DeviceSubnet, self).__init__(*args, **kwargs) Exception Type: TypeError at /config/device_details/2/7 Exception Value: super(type, obj): obj must be an instance or subtype of type This is the function within the view if request.method == 'GET': form = DeviceSubnetForm() else: # A POST request: Handle Form Upload form = DeviceSubnetForm(request.POST) # If data is valid, proceeds to create a new post and redirect the user if form.is_valid(): subnet_data = form.save(commit=False) obj, record = DeviceSubnet.objects.update_or_create( defaults={ 'subnet' : subnet_data.subnet, 'subnet_mask' : subnet_data.subnet_mask, 'subnet_type' : SubnetTypes.objects.get(subnet_data.subnet_type) }, subnet=subnet_data.subnet, subnet_mask=subnet_data.subnet_mask, subnet_type=SubnetTypes.objects.get(subnet_data.subnet_type) ) print(obj.id) return 'Valid' -
Filling form with csv file data Django
What I am trying to do is filling Django form with data coming from CSV file. Idea is to let user choose whether he wants to fill a form by himself or do this by uploading data from csv file. I have been looking for a tip on stackoverflow for some time already and haven't found anything else then saving data to django-models and retrieve them later on. I don't want to save the file anywhere neither. I don't want to use django models to save the data and then upload them into a form and I was wondering - is there any way to accomplish such? Simple code to explain this a bit more: #template.html <form action="/generate/" method="post"> First name: {{ form.first_name }}<br> Last name: {{ form.last_name }}<br> <input type="submit" value="Submit" /> </form> <form method="POST" action="/upload" enctype="multipart/form-data"> <div class="form-group"> <label for="inputFile">File input</label> <input type="file" name="inputFile"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> I would like to 2nd form reads the file and somehow fill with data the upper one on the same page / template to allow further validating and actions under this view. Does anyone have any ideas ? -
Filtering in ManytoManyField
How to make a choice only from users who are in the group created in the admin panel? owner = models.ManyToManyField(User, verbose_name = 'Исполнитель') -
Django customize ForeignKey way of instances returnment
I have a need to create custom field, that is very similar to a ForeignKey field but has specific logic. Two main tasks are: Each related model of this CustomForeignKey has regular ForeignKey field to the model itself and my purpose is to return one of this instances depending on some parameter (date for example). Maybe it would be more clear with some example: class Author(models.Model): name = models.CharField(max_length = 30) surname = models.CharField(max_length = 60) publication = CustomForeignKey(Publication) class Publication(models.Model): title = models.CharField(max_length = 50) text = models.TextField() date = models.DateTimeField() source = models.ForeigKey('self', related_name='references') I want calls to SomeAuthor.publication be performed like SomePublication.references.order_by('date').first(). Real goal is more difficult, but the sense is nearly the same. Second thing is about lookups. When I filter objects by this CustomForeignKey, I would like to have same logic as in previous point. So Author.objects.filter(publication__title = 'Some Title') should make filtering by the fist object ordered by date from references related manager. I read the documentation about creating custom fields in django, but there are no good examples about custom relational fields. In django.db.models.fields.related as well, I didn't find which methods should I redefine to achieve my goal. There are to_python and from_db_value, … -
ChoiceBlock consisting of other Wagtail blocks?
I'm trying to construct the carousel model: class Carousel(blocks.StructBlock): heading = blocks.CharBlock(required=False) carousel = blocks.ListBlock( blocks.StructBlock([ ('slide', blocks.StreamBlock([ ('image', ImageChooserBlock()), ('video', EmbedBlock())]), ), ('description', blocks.RichTextBlock()), ]) ) Every slide consists of one image or video and a description. I'm using StreamBlock in here because I couldn't find any other more suitable structural block type which would allow to the user to choose between image and video. Ideally I need something similar to the ChoiceBlock, except that the choices argument should expect other block types. Is that feasible? Or at least is there a way to limit how many sub-blocks might be inserted from within the StreamBlock? -
Best practice to divide a django project into applications
I want to know how to divide a project having a hierarchical structure into applications. Let's say that I'm trying to build up something like github.com for example. In github.com, an account has some repositories, which have some features like code, issues or pull requests. And those features have references to other features. In this case, which is an application and which is not? At that time, should I put applications in the root directory or in an application directory as sub-applications? -
celery tasks: update state after try & except block
I have celery 4.1.0, django 1.11.11, rabbitMQ and Redis for results. @shared_task(bind=True) def one_task(self): try: ... some db stuff here ... except BaseException as error: self.update_state(state='FAILURE', meta={'notes': 'some notes'}) logger.error('Error Message ', exc_info=True, extra={'error': error}) So, when my code runs into except block self.update_state does not work but logger works... Actually, I'm not sure if @shared_task(bin=True) it's right... What I want to do it's catch exceptions(through try & except blocks) of my python code, change states and terminate the tasks manually. So, any advise/help? -
Changes made to code not getting reflected on a django app with nginx and gunicorn
I have already tried the systemctl restart gunicorn/nginx and have already deleted the cached files ending with .pyc. Anyone got any solutions other than this? The site is running on an ubuntu ec2 instance of aws -
The best framework for the Web (With server-side python) [on hold]
I will explain the need: I am starting a project in my graduation project and I would like to create a platform (Python with other language for interfaces), and here is the approach: I thought about Wordpress and I already posted a subject in this way, but I can not do related Wordpress and Python (I do not find a plugin for that) There is Django and Flask (I'm looking for something that can give me a very good interface, I have to work a lot on the designated side) I am open to your proposals stp. Thank you very much. Regards, -
Django rest disable templates for only return data
Environment: Python 3.6 Django 2.0 Django REST 3 I am connecting a django project with an android application and everything has worked correctly but I have a problem that anyone who accesses the url of the requests in android can see that data. I want to block that render or template and only return the json data that I need for my android application. myapp/View.py class restContact(APIView): def get(self, request): allcontact = Contact.objects.all() serializer = ContactSerializer(allcontact, many=True) return Response({"state":"1","control":serializer.data},status=status.HTTP_400_BAD_REQUEST) myapp/Url.py from django.contrib import admin from django.conf.urls import url,include from apps.my-app.views import restContact urlpatterns = [ url(r'^contacts/$', restContact.as_view()), ] proyect/url.py from django.conf.urls import url from django.urls import include from django.contrib import admin urlpatterns = [ url(r'',include('apps.index.urls')), url(r'^admin/', admin.site.urls), url(r'^index/',include('apps.index.urls')), url(r'^movil/', include('apps.myapp.urls')), ] I just need to return jsonObject and in the browser to write the url www.mypage.com/movil/contacts can not see all the data in the get. -
Django: Filter a Queryset made of unions not working
I defined 3 models related with M2M relationsships class Suite(models.Model): name = models.CharField(max_length=250) title = models.CharField(max_length=250) icon = models.CharField(max_length=250) def __str__(self): return self.title class Role(models.Model): name = models.CharField(max_length=250) title = models.CharField(max_length=250) suites = models.ManyToManyField(Suite) services = models.ManyToManyField(Service) Actions = models.ManyToManyField(Action) users = models.ManyToManyField(User) def __str__(self): return self.title In one of my views I tried to collect all the Suites related to an specific User. The user may be related to several Roles that can contain many suites. And then filter Suits by name. But the filter seem to have no effects queryset = Suite.objects.union(*(role.suites.all() for role in self.get_user().role_set.all())) repr(self.queryset) '<QuerySet [<Suite: energia>, <Suite: waste 4 thing>]>' self.queryset = self.queryset.filter(name="energia") repr(self.queryset) '<QuerySet [<Suite: energia>, <Suite: waste 4 thing>]>' The query atribute inside the queryset not alter its content before executin the filter: (SELECT "navbar_suite"."id", "navbar_suite"."name", "navbar_suite"."title", "navbar_suite"."icon" FROM "navbar_suite") UNION (SELECT "navbar_suite"."id", "navbar_suite"."name", "navbar_suite"."title", "navbar_suite"."icon" FROM "navbar_suite" INNER JOIN "navbar_role_suites" ON ("navbar_suite"."id" = "navbar_role_suites"."suite_id") WHERE "navbar_role_suites"."role_id" = 1) (SELECT "navbar_suite"."id", "navbar_suite"."name", "navbar_suite"."title", "navbar_suite"."icon" FROM "navbar_suite") UNION (SELECT "navbar_suite"."id", "navbar_suite"."name", "navbar_suite"."title", "navbar_suite"."icon" FROM "navbar_suite" INNER JOIN "navbar_role_suites" ON ("navbar_suite"."id" = "navbar_role_suites"."suite_id") WHERE "navbar_role_suites"."role_id" = 1) -
Apps deployed on Heroku do not reflect on a part of programme although they can work on local server
This application was developed through Djangogirls tutorial (https://tutorial.djangogirls.org/en/django_forms/). I would like to know how to find out the reason and fix them. I dont get why those kinds of problems happens as the blow pictures show. The local server: Everything does work correctly and I just would like to make this work on heroku enter image description here Apps deployed on Heroku: Any post does not show up although I think that I push correctly files on heroku enter image description here What I already did was here: 1) restart heroku and relaunch apps 2) clear cache of chrome and reload apps 3) check git log 4) commit and push again (git push heroku master) What should I do next ? See how data migration is working but I do not know how to check ... -
How to customize database connection settings' timezone in django?
I am looking into django db backends. I have found that datetime values' timezone are changed to and forth by django, while saving dates into db as well as retrieving them. During this conversion process, django uses database connection's timezone settings. I have seen that by default for sqlite db, 'UTC' is the timezone. I want to change the database connections options, during the start of django application. How can I do that ? Thanks in advance. -
I'm overlooking something: TypeError: create() got unexpected keyword argument 'system'
It's probably a noob mistake, but I cant find the error. Below is the project.models class ProjectManager(models.Manager): """""" def create(self, owner, project_name): project = super().create(owner=owner, project_name=project_name) project.save() System.objects.create(project=project, system_name="System initial name") return project class Project(models.Model): objects = ProjectManager() owner = models.ForeignKey('auth.User', related_name='projects', on_delete=models.CASCADE) project_name = models.CharField(max_length=200) In the system.models I now define the System and Circuit model, i.e. each project has at least one System and each System has at least one circuit. class SystemManager(models.Manager): """""" def create(self, project, system_name): system = super().create(project=project, system_name=system_name) system.save() Circuit.objects.create(system=system, circuit_name="Primary circuit") return system class System(models.Model): objects = SystemManager() project = models.ForeignKey('solgeo.Project', related_name='systems', on_delete=models.CASCADE) system_name = models.CharField(max_length=200) @classmethod def create(cls, project): system = cls(project=project) def __str__(self): return "system name: " + str(self.system_name) class CircuitManager(models.Manager): """""" def create(self, project, system_name): circuit = super().create(system=system, circuit_name=circuit_name) circuit.save() return circuit class Circuit(models.Model): """Models a hydraulic circuit""" objects = CircuitManager() system = models.ForeignKey(System, related_name='circuits', on_delete=models.CASCADE) circuit_name = models.CharField(max_length=200) Now I get the error: create() got an unexpected keyword argument 'system'. When I comment out: Circuit.objects.create(system=system, circuit_name="Primary circuit") then the error disappears. -
How to have Google Places Autocomplete work with AMP?
I'm trying to convert this homepage to AMP: excurj.com. Is there a way to keep the Autocomplete feature on the hero search field ? I saw this question. However, I need these two scripts to make autocomplete work: <script src="{% static 'js/autocomplete.js' %}"></script> <script src="https://maps.googleapis.com/maps/api/js?key=*****&callback=initMap&libraries=places"></script> This is what's inside autocomplete.js: // script to auto complete location function initMap() { var defaultBounds = new google.maps.LatLngBounds( new google.maps.LatLng(-90, 91), new google.maps.LatLng(-180, 80)); var options = { types: ['(cities)'], bounds: defaultBounds }; var input = document.getElementById('google_city_search'); var autocomplete = new google.maps.places.Autocomplete(input, options); } -
Django Form validation without a form.py
Is it possible to do form validation on a field that is created by html only? In example: <select class="form-control my_boolean" id="required_courseid" name = "required_course" > <option value = ""> Is this a required course? </option> <option value = "0"> No </option> <option value = "1"> Yes </option> </select> Before hitting the submit button I want to display an error if the user hasn't selected this option. Similiar to the .clean function i've read about. I do have a form created in the html as <form action = "{% url 'result' %}" form method = "POST"> I'm not using a class for the form in form.py since it's all done in the html. Did I go about this the wrong way, please offer suggestions. -
Share models between multiple apps and multiple database without code duplication (django)
I'm currently developing a web app in Django. My app is dealing with vegetables and gardens. A garden can have its own vegetables, but I would like it to be able to import vegetables from a common library/encyclopedia. Diagram of the models in the main app and in the library A first idea was to have a garden_id for all vegetables and set it to 0 or None for vegetables of the library but then the library isn't really reusable and is tightly coupled to the main app. A second idea was that vegetables linked to garden inherit from vegetables from library, but inheritance tends to be tricky with Django. A last idea that I use for the moment, is to create a second django app for the vegetable library and duplicate the vegetable model (in the main and the library app). I plan to implement an "import" module, that would convert vegetables from the library to vegetables linked to a garden. I also have two databases, one for the main app and one containing the common vegetables ( Can i use different databases for different apps in django ) Duplication is never a good idea, but I can't find … -
django url with or condition
I have an app in django - 1.11. When changing the language in the template, the address appears: localhost:8000/en/events/None/None/None Below solution is OK. My question is it possible to join these 4 regexes with one regex? For example, add something like or into regex? My dirty solution with few url regex: url(r'^$', views.ListView.as_view(), name='list'), url(r'^(?:/(?P<filter1>[a-zA-Z0-9-]+))?$', views.ListView.as_view(), name='list'), url(r'^(?:/(?P<filter1>[a-zA-Z0-9-]+))?(?:/(?P<filter2>[a-zA-Z0-9-]+))?$', views.ListView.as_view(), name='list'), url(r'^(?:/(?P<filter1>[a-zA-Z0-9-]+))?(?:/(?P<filter2>[a-zA-Z0-9-]+))?(?:/(?P<filter3>[a-zA-Z0-9-]+))?$', views.ListView.as_view(), name='list'), -
django file not found error: when javacript file inside static directory trying to access another file in the static directory?
I am doing one django project. And I am able to access the "custom.js" file from static folder path.This is a line inside my "index.html" file. <script type="text/javascript" src="{% static 'crypto_app/js/custom.js' %}" ></script> But inside "custom.js" file it is using this : $(window).ready(function() { 'use strict'; $.vegas('slideshow', { backgrounds:[ { src: 'images/bg-slider/bg-1.jpg', fade:1000 }, { src:'images/bg-slider/bg-2.jpg', fade:1000 }, { src:'images/bg-slider/bg-3.jpg', fade:1000 } })(); And hence, due to wrong file address, I am not able to access the images. And it is showing file not found. Is there some django way to declare path of images as variable and accessing it from the "custom.js" file? Given below is my directory structure : | admin.py | apps.py | models.py | tests.py | tree.txt | urls.py | views.py | +---migrations | | __init__.py| +---static | \---crypto_app | +---css | | | +---fonts | +---images | | \---bg-slider | | bg-1.jpg | | bg-2.jpg | | bg-3.jpg | | | \---js | custom.js +---templates | \---crypto_app | index.html -
Insert new section into Django Admin UserChangeForm
I am adding a section to the end of UserChangeForm using this code. from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from apps.auth_app.models import UserProfile class ProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'Profile' class ProfileAdmin(UserAdmin): inlines = [ ProfileInline, ] admin.site.unregister(User) admin.site.register(User, ProfileAdmin) I would rather insert that section of code after "Personal info", but have been unable to find a way to do this with just the fieldset. I have found examples like this, but is there a way to do this without having to subclass all of the Django Admin User Form? class UserAdmin(auth_admin.UserAdmin): fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name')}), ('<<Custom Fields>>', {'fields': (<<Field Names>>)}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ) ... form = UserChangeForm -
jquery hidden div remove field required
How to remove required in hidden fields. It must remain required in visible field.When one of the options is selected, the required field needs to be removed. This form created django framework. For example, when "tuzel" is selected, the required field needs to be removed from the adi field. Jquery Code <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("select").change(function(){ $(this).find("option:selected").each(function(){ var optionValue = $(this).attr("value"); if(optionValue){ $(".col").not("." + optionValue).hide(); $("." + optionValue).show(); } else{ $(".col").hide(); } }); }).change(); }); </script> <select name="secenek" class="form-control select2" required id="id_secenek"> <option value="" selected>---------</option> <option value="tuzel">Tüzel</option> <option value="gercek">Gerçek</option> </select> <div class="tuzel col col-lg-6"> <div id="fnWrapper" class=" parsley-input"> <label class="form-control-label">Firma Ünvanı: <span class="tx-danger">*</span></label> <input type="text" name="firma_adi" class="form-control" id="id_firma_adi" maxlength="256" required/> </div> </div><!-- col-4 --> <div class="gercek col col-lg-6"> <div id="fnWrapper" class=" parsley-input"> <label class="form-control-label">Adı: <span class="tx-danger">*</span></label> <input type="text" name="adi" data-parsley-class-handler="#fnWrappe" class="form-control" required="True" id="id_adi" maxlength="128" required/> </div> </div><!-- col-4 --> -
Django and Celery (Threads issue)
I have a problem with an idea that I have in mind but to achieve it I need a lot of machine resources. The idea is the following: Create a web system, with django, in which there are several users (suppose there are many); each user can create one or several processes (around 200 processes) that execute code indefinitely on the server (it can take up to days to give a result), for the process creation management I'm using celery (which I do not know if it's the Better option). I know that this is very expensive for the server, so my question is: Is it possible to achieve this task without spending so many machine resources? As I understand celery works with threads, which are supposed to be lighter than creating new processes, but in the same way it is too expensive for the given problem. -
Django include partial fields just once
I got a partials html with some form fields set. Actually, in my template i use the include tag for this partial with every field as i show in this code: <div class="row"> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="vertical" field=form.gender type="select2" addon="fa-intersex" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="inline" field=form.blood_type type="select2" addon="fa-tint" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="inline" field=form.rh_factor label_set="Factor" type="select2" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="vertical" field=form.civil_status type="select2" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="vertical" field=form.native_language type="select2" addon="fa-language" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="vertical" field=form.race type="select2" %}</div> </div> <div class="row"> <fieldset> <legend >Contacto</legend > <div class="col-md-4 col-lg-3">{% include "partials/field.html" with form_type="vertical" field=form.email type="email" addon="fa-envelope" %}</div> <div class="col-md-4 col-lg-3">{% include "partials/field.html" with form_type="vertical" field=form.email_additional type="email" addon="fa-envelope" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="vertical" field=form.cell_phone addon="fa-mobile" %}</div> <div class="col-md-2 col-lg-2">{% include "partials/field.html" with form_type="vertical" field=form_residence.telephone addon="fa-phone" %}</div> </fiedset> </div> Like that many times, so, template takes quite long to render....is there a way to make only one include and then call the fields without that tag and improve time and efficiency in template render ?? Thanks in advance -
can't get image to load
I probably did something stupid but when i upload a image with /admin I can't get it to load. I made a for loop to get all post's and everything shows except for the image model: `class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField() image = models.ImageField(upload_to='blog/media/photos') date = models.DateTimeField()` template page: ` {% for post in object_list %} <h5><a href="/blog/{{post.id}}">{{post.title}}</a></h5> <img src="{{ post.image.url }}"> <h1>{{ post.image.url }}</h1> {% endfor %}`