Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: 'list' object is not callable | DRF exception handling
I am trying to parse Django model ValidationError into DRF ValidationError. But I keep getting the following output: TypeError: 'list' object is not callable Here is my custom exception handler: import logging from django.core.exceptions import ValidationError as DjangoValidationError from rest_framework.exceptions import ValidationError LOG = logging.getLogger(__name__) def transform_exception(exception): """Transform model validation errors into an equivalent \ DRF ValidationError. After reading the references, you may decide not to use this. References: https://www.kye.id.au/blog/understanding-django-rest-framework-model-full-clean/ https://www.dabapps.com/blog/django-models-and-encapsulation/ """ if isinstance(exception, DjangoValidationError): if hasattr(exception, "message_dict"): detail = exception.message_dict elif hasattr(exception, "message"): detail = exception.message elif hasattr(exception, "messages"): detail = exception.messages else: LOG.error("BAD VALIDATION MESSAGE: %s", exception) exception = ValidationError(detail=detail) return exception And here is my error log: Server Logs Where am I going wrong? -
For development purpose, how can I open a Django Jinjia2 template in browser with preliminary rendering (extending, including)?
Problem description I am starting working on a Django project and the server-side rendering template is a little hard to work with. Usually I develop the front-end application with hot module reload server so that I can see the rendered page during development. However, for Django project I can only view the site by serving and open from browser. If I open the template directly, the include, extends are not processed, hence CSS and JavaScript are not loaded in the base template. My question is, is there any tool or workflow that can help develop the Django template in offline so that the style and layout can be rendered properly during development? Thank you -
how get longitude and latitude of users geodjango
i'm new to geodjango i want to make real world gis project with geodjango to find locations i tried this class Place(models.Model): user= models.ForeignKey(Account,on_delete=models.CASCADE) address = models.CharField(max_length=100) slug = models.SlugField(unique=True,blank=True,null=True) description = models.TextField() location = models.PointField(srid=4326) views.py class PalceCreateApiView(CreateAPIView): queryset = Place.objects.all() serializer_class = PlaceCreateSerializer def perform_create(self,serializer): address = serializer.initial_data['address'] g = geocoder.google(address) lat = g.latlng[0] lon = g.latlng[1] point = f'POINT({lat} {lon})' serializer.save(user=self.request.user,location=point) but i want to get exact location ,because sometimes the user cant write the same address name , so the coordiantes been wrong how to access users location then assign to location field thanks i'm new to geodjango if someone can recommend me an open source project i appreciate it -
trying to submit a view and getting 405 error
I'm trying to implement a review section in a user profile but I keep getting this 405 error when i try to submit a review even tho when i create a review in the admin panel it shows on the profile normaly. if you could help. Thanks in advance Code: Model class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) expert = models.ForeignKey(Expert, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField() Form class ReviewForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={ 'rows':3, })) class Meta: model = Review fields = ('content',) View class ExpertDetailView(DetailView): model = Expert def expert(self, *args, **kwargs): form = ReviewForm(self.request.POST) if form.is_valid(): expert = self.get_object() review = form.instance review.user = self.request.user review.expert = expert review.save() print ('worked') print ('worked') def get_object(self, **kwargs): object = super().get_object(**kwargs) return object def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'form': ReviewForm() }) return context And finaly the Template <h4>Leave a comment below</h4> <form method='POST'> {% csrf_token %} {{ form|crispy}} <br> <button class='btn btn-primary' type='submit'>review</button> </form> <hr /> <h5>Comments</h5> {% for review in object.reviews %} <div> <p>{{ review.content }} <br /> <small>{{ review.timestamp|timesince }} ago</small> </div> <hr /> {% endfor %} -
orderin en el models de django no me devuelve el template de forma correcta
tengo un frontend que muestra cuadros de servicios de esta formaimagen del diseño original pero en el momento de hacer runserver se me muestra tipo cascada y no como tabla. como en el diseño original. diseño de lo que me devuelve el admin class Post(models.Model): title = models.CharField(max_length=200, verbose_name='Titulo') content = models.TextField(verbose_name='Contenido') image = models.ImageField(verbose_name='Imagen', upload_to='Projects') created = models.DateTimeField(auto_now_add='True', verbose_name="Fecha de creacion") updated = models.DateTimeField(auto_now='True', verbose_name="Fecha de edicion") class Meta: verbose_name = "Entrada" verbose_name_plural = "Entradas" ordering = ['created'] def __str__(self): return self.title ahora tengo el template asi. {% for projects in projects %} <div class="fullwidth-block"> <div class="container"> <div class="project-list"> <div class="project"> <div class="project-content"> <figure class="project-image"><img src="{{projects.image.url}}" alt=""></figure> <h3 class="project-title">{{projects.title}}</h3> <p>{{projects.content}}</p> <a href="project.html" class="button">Learn more</a> </div> </div> </div> </div> </div> </main> <!-- .main-content --> {% endfor %} como hago para que respete el diseño original de estilo tabla. gracias -
how can i solve this urls in Django
here is the code of my project url: from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('',include('calculator.urls')), path('admin/', admin.site.urls), ] here is the code of my app url: from django.urls import path from . import views urlpartterns = [ path('',views.Courses, name='home-page') ] code for views.py: from django.shortcuts import render from django.http import HttpResponse def Courses(request): return HttpResponse('Hello world') enter image description here Error: django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Django: Operate on User Input
I have created a django model with a Decimal field. I would like to make it so that when the user inputs a number, the value that is saved is multiplied by 2. I have tried updating the sqlite database with the python sqlite module but gave up after a while. Any ideas on how I can maybe use managers or something of the sort? -
grepelli issue with autocomplete_search_fields
class Billing1500(models.Model): Practice = models.ForeignKey('DemoPractice', on_delete=models.CASCADE) Provider = models.ForeignKey('DemoProvider', on_delete=models.CASCADE) PatiName = models.CharField(max_length=255, null=True, blank=True, help_text='Last Name, First Name') PatiDOB = models.CharField(max_length=255, null=True, blank=True) PatiSex = models.CharField(max_length=255, null=True, blank=True) ICD1 = models.CharField(max_length=8, null=True, blank=True) ICD2 = models.CharField(max_length=8, null=True, blank=True) ICD3 = models.CharField(max_length=8, null=True, blank=True) ICD4 = models.CharField(max_length=8, null=True, blank=True) ICD5 = models.CharField(max_length=8, null=True, blank=True) ICD6 = models.CharField(max_length=8, null=True, blank=True) ICD7 = models.CharField(max_length=8, null=True, blank=True) ICD8 = models.CharField(max_length=8, null=True, blank=True) ICD9 = models.CharField(max_length=8, null=True, blank=True) ICD10 = models.CharField(max_length=8, null=True, blank=True) ICD11 = models.CharField(max_length=8, null=True, blank=True) ICD12 = models.CharField(max_length=8, null=True, blank=True) CPT1 = models.CharField(max_length=8, null=True, blank=True) CPT6 = models.CharField(max_length=8, null=True, blank=True) @staticmethod def autocomplete_search_fields(): return ("Provider_icontains", ) @admin.register(Billing1500) class Billing1500(admin.ModelAdmin): raw_id_fields = ('Provider',) autocomplete_lookup_fields = { 'fk': ['Provider'], } class Media: js = ( 'js/admin/bootstrap.bundle.js', 'js/admin/bootstrap.js', ) css = { 'all': ( 'css/admin/bootstrap.css', 'css/admin/bootstrap-grid.css', 'css/admin/bootstrap-reboot.css', ) } pass i'm trying to have autocomplete search fields in my grapellie admin models, however im getting errors when trying to bind my foreignkeys to my grappelli function. i'm having the following issue ERRORS: ?: (grappelli.E001) Model Core.billing1500 returned bad entries for autocomplete_search_fields: Provider_icontains HINT: A QuerySet for {model} could not be constructed. Fix the autocomplete_search_fields on it to return valid lookups. reading the docs it … -
Filtering django foreignkey dropdown relative to other field in same model
So essentially I'm using django-nested-admin to create a "quiz" type model where the admin can add custom questions and answers to those questions. The issue now is that the admin view can't distinguish which answers belong to which questions, so everytime a user goes to select an answer choice, they are able to select from every answer for every question ever created. I've included a photo of what this looks like from the admin. I've tried overriding the formfield_foreign_key form for the admin, and have been able to filter the shown answer choices by hardcoding a question id. However, I want to be able to filter the answers based on the question associated with the response and am having trouble doing so. Can anybody provide any insight? Thanks in advance. Answers all mixed up in response admin view: Answers filtered via a hardcoded id: Current code which filters based on hardcoded question_id: class ResponseInline(admin.TabularInline): model = Response def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "answer": kwargs["queryset"] = Answer.objects.filter(question_id = 1) return super().formfield_for_foreignkey(db_field, request, **kwargs) My current Response model in models.py: class Response(models.Model): question_form = models.ForeignKey(AdditionalQuestions, on_delete=models.CASCADE, null=True) user = models.ForeignKey(Profile, on_delete=models.CASCADE, null = True) question = models.ForeignKey(Question, on_delete=models.CASCADE, null=True) … -
Django user customization database tables
I am trying to build a Django website where the user is able to create custom objects known as items. Each item needs to be able to have certain properties that are stored in the database. For example an item would need properties such as Serial Number, Description, Manufacture Date However I want the user to be able to specify these fields similar to what Microsoft dynamics allows . For example a user should be able to specify they want a text field with the name Model Number, associated with a specific item type and from then on they can store those properties in the database. I am not sure the best approach to do this because a standard database model, you already have all the fields defined for a specific table, however this essentially means i have to find a way to have user defined tables. Does anyone know a good approach to handle this problem, at the end of the day I want to store items with custom properties as defined by the user in a database. thanks -
Ho to create download link in django
I created a django project which I use in Apache server. The project simply edit an m3u file when press the button on a page and generates a new m3u file. The script works as intended. So the question is that is it possible Django can generate a download link automatically for this newly generated m3u file? I understand from many tutorials that I need to edit urls.py and view.py files but I need it to be done automatically. Or another option would be to make the file downloadable via apache diretly if something like this is possible. -
pwa and chrome same time
I have a website with authentication google, and this work fine. But, my website is PWA, then when I use the web in mobile, then open login google with pwa automatically and this don't work fine, because, I have error. But when I return to website, website have login but PWA have error. How can I to keep the login with browser when I open the web with browser. -
How can I solve this issue in django without changing the models?
Info I have two simple models in Django, with one-to-one relationship I'm using generic views There are Issues and Solutionss in the database, numbered 1 through 10 Loading the Issue via the DetailView (e.g. localhost:8000/myapp/6/) works great Error When trying to load the Solution view in a browser (e.g. localhost:8000/myapp/6/solution/), I get Page not found (404), No solution found matching the query. Code models.py: class Issue(models.Model): def __str__(self): return self.issue_text issue_text = models.CharField(max_length=200) class Solution(models.Model): def __str__(self): return self.solution_text issue = models.OneToOneField(Issue, on_delete=models.CASCADE) solution_text = models.CharField(max_length=200) views.py: class DetailView(generic.DetailView): model = Issue template_name = 'my_templates/detail.html' class SolutionView(generic.DetailView): model = Solution template_name = 'my_templates/solution.html' urls.py: urlpatterns = [ url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/solution/$', views.SolutionView.as_view(), name='solution'), ] Question I think that pk is not passed correctly, so that the url is read in urls.py but can't find an instance of Solution since "there's no link" between the models... or something like that. I've been going through Django's docs on generic views and making Django queries to the database but I think I'm confusing the two. Also, debugging with pdb just makes the browser lose the object for some reason. Did I get the one-to-one relationship backwards? Is there a way to make this … -
Pre-populate Django form ChoiceField with instance data
Help needed with pre-populating Django forms: I have a form that updates a UserProfile model, when the form is loaded I want it pre-populated with the existing UserProfile data. Simple enough, the instance can be passed to the form. However, it seems that fields with choices (which come out as select drop-down elements in HTML) are not pre-populated with the instance data and instead default to '-----------'. I've tried manually setting the initial value for a specific form (e.g. country) but it doesn't pull through to the HTML. form = UserProfileForm(instance=user_profile) form.fields['country'].initial = 'GBR' I'm sure I could create a convoluted work around to get the current country selected in the front-end but it feels like it should be possible in Django. I couldn't see any solutions in other questions so would be grateful of any help with this. -
Using Django views when importing a external module with multiprocessing
I built a scraping module "scraper.py" that also has the ability to download file and I imported this module into django views. Issue is that in the scraper.py, this " __name__='__main__" is included where the multiprocessing pool is, so when I import the module and try to run it, it doesn't work because it isn't the main. This is the script(scraper.py) that uses the pool method. def download(self, url): response = self._is_downloadable(url) if response: name = response.headers.get('content-disposition') fname = re.findall('filename=(.+)', name) if len(fname) != 0: filename = fname[0] filename = filename.replace("\"", "") print(filename) else : filename = "Lecture note" with open(filename, 'wb') as files: for chunk in response.iter_content(100000): files.write(chunk) def download_course_file(self, course): username = self._login_data["username"] p = Path(f"{username}-{course}.txt").exists() if not p: self.get_download_links(course) statime = time.time() if __name__ == "__main__": with Pool() as p: with open(f"{username}-{course}.txt", "r") as course_link: data = course_link.read().splitlines(False)[::2] p.map(self.download, data) print(data) print(f"Process done {time.time()-statime}") This module is imported in the views and then ran as import scraper def download_course(request, id): course = course = get_object_or_404(Course, id=id) course_name = (course.course_name)[:6] person, error = create_session(request) if "invalid" in error: data = {"error":error} return JsonResponse(data) person.download_course_file(course_name) data = {"success":"Your notes are being downloaded"} return JsonResponse(data) PS: create_session is a function … -
ManyToMany Relationship between two models in Django
I am trying to build a website that users can add the courses they are taking. I want to know how should I add the ManyToMany relationship. Such that we can get all users in a course based on the course code or instructor or any field. And we can also get the courses user is enrolled in. Currently, my Database structure is: class Course(models.Model): course_code = models.CharField(max_length=20) course_university = models.CharField(max_length=100) course_instructor = models.CharField(max_length=100) course_year = models.IntegerField(('year'), validators=[MinValueValidator(1984), max_value_current_year]) def __str__(self): return self.course_code and my user model: class Profile(AbstractUser): bio = models.TextField() image = models.ImageField(default='defaults/user/default_u_i.png', courses = models.ManyToManyField('home.Course',related_name='courses') def __str__(self): return self.username I was wondering should ManyToMany relationship be in User model or the course model? Or will it make any difference at all? -
Multiprocessing with Django when importing a external module
I built a scraping module "scraper.py" that also has the ability to download file and I imported this module into django views. Issue is that in the scraper.py, this " __name__='__main__" is included where the multiprocessing pool is, so when I import the module and try to run it, it doesn't work because it isn't the main. This is the script(scraper.py) that uses the pool method. def download(self, url): response = self._is_downloadable(url) if response: name = response.headers.get('content-disposition') fname = re.findall('filename=(.+)', name) if len(fname) != 0: filename = fname[0] filename = filename.replace("\"", "") print(filename) else : filename = "Lecture note" with open(filename, 'wb') as files: for chunk in response.iter_content(100000): files.write(chunk) def download_course_file(self, course): username = self._login_data["username"] p = Path(f"{username}-{course}.txt").exists() if not p: self.get_download_links(course) statime = time.time() if __name__ == "__main__": with Pool() as p: with open(f"{username}-{course}.txt", "r") as course_link: data = course_link.read().splitlines(False)[::2] p.map(self.download, data) print(data) print(f"Process done {time.time()-statime}") This module is imported in the views and then ran as import scraper def download_course(request, id): course = course = get_object_or_404(Course, id=id) course_name = (course.course_name)[:6] person, error = create_session(request) if "invalid" in error: data = {"error":error} return JsonResponse(data) person.download_course_file(course_name) data = {"success":"Your notes are being downloaded"} return JsonResponse(data) PS: create_session is a function … -
TypeError: Direct assignment to the reverse side of a related set is prohibited
I have a Django model 'Restaurant' which has a field parent_rest_id, which refers to one its parent restaurant which is saved in same table. class Restaurant(DefaultColumns): name = models.CharField(null=False, max_length=40) restaurant_code = models.CharField(null=False, max_length=40, default='') parent_rest_id = models.ForeignKey('self', null=False, db_column='parent_id', default=0, related_name='parent_id', on_delete=models.CASCADE) restaurant_type = models.ForeignKey(RestaurantType, null=False, default='10', db_column='restaurant_type', related_name='restaurant_type', on_delete=models.DO_NOTHING) Now when I try to create a row for it, I get this error "TypeError: Direct assignment to the reverse side of a related set is prohibited. Use parent_id.set() instead." I have made sure the parent_id is instance of Model Restaurant(Restaunt.objects.get(id=1)) Please let me know what I am doing wrong or I have created my model wrong, I am new to django. PS: I don't have any customized serializer or model manager. And DefaultColumns is parent class which inherits from model.Models -
ModuleNotFoundError: No module named 'django', with virtual environment Python3.8
Trying to run Django App along with Apache2 in Python3.8 Virtual environment. When I enter in to the python shell, I could import django. But when accessing webpage, it says "django not found" As per the /var/log/apache2/error.log, following is the error [Sun May 03 02:56:14.209910 2020] [wsgi:error] [pid 21516] [remote 192.168.1.5:58968] from django.core.wsgi import get_wsgi_application [Sun May 03 02:56:14.209966 2020] [wsgi:error] [pid 21516] [remote 192.168.1.5:58968] ModuleNotFoundError: No module named 'django' wsgi.py: import os,sys sys.path.append('/var/www/html/django-venv-py3.8/lib/python3.8/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'filebucket.settings') application = get_wsgi_application() default.conf (django-venv-py3.8) ramesh@Orktion:.../filebucket$ cat /etc/apache2/sites-available/000-default.conf <Directory /var/www/html/django-venv-py3.8/filebucket/filebucket> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess filebucket python-path=/var/www/html/django-venv-py3.8/filebucket python-home=/var/www/html/django-venv-py3.8 WSGIProcessGroup filebucket WSGIScriptAlias / /var/www/html/django-venv-py3.8/filebucket/filebucket/wsgi.py Alias /static /var/www/html/django-venv-py3.8/filebucket/static <Directory /var/www/html/django-venv-py3.8/filebucket/static> Require all granted </Directory> Alias /media /var/www/html/django-venv-py3.8/filebucket/media <Directory /var/www/html/django-venv-py3.8/filebucket/media> Require all granted </Directory> I have followed some troubleshooting articles, but no luck -
Problem cors Issue in a request XMLHttpRequest
I want to solve the problem when I request a request in pythoanywhere the request requests path an addition to the domain and path I just want to add the domain only, without the path, how is that? Please note that I use cors in Django export function backendLookup(method, endpoint, callback, data) { let jsonData; if (data) { jsonData = JSON.stringify(data); } const xhr = new XMLHttpRequest(); const url = `api${endpoint}`; xhr.responseType = "json"; const csrftoken = getCookie("csrftoken"); xhr.open(method, url); xhr.setRequestHeader("Content-Type", "application/json"); if (csrftoken) { // xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest") xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("X-CSRFToken", csrftoken); } xhr.onload = function () { if (xhr.status === 403) { const detail = xhr.response.detail; if (detail === "Authentication credentials were not provided.") { if (window.location.href.indexOf("login") === -1) { window.location.href = "/login?showLoginRequired=true"; } } } callback(xhr.response, xhr.status); }; xhr.onerror = function (e) { callback( { message: "The request was an error", }, 400 ); }; xhr.send(jsonData); } Meaning when I enter the link in the browser: http://tweet.pythonanywhere.com/global/ The api link converts the domain and path: http://tweet.pythonanywhere.com/global/api/tweets/ And I just want to add only the domain, how is that: http://tweet.pythonanywhere.com/api/tweets/ -
remove empty div and parent
Hello I have a HTML that shows all the artworks based on their collections as bellow:now, the collection "No_COLLECTION" is empty but it shows it's collection name and an empty space. I tried to remove it but i couldn't. Please help me to remove all the collections that doesn't have artworks in them. {% extends "base.html" %} {% load static %} {% block content %} <div id="main" style='min-height:800px;'> {% with 'No_COLLECTION woodtest Test-2 Culture KASHAN HUMAN mine' as list %} {% for i in list.split %} <script> var level = 0; </script> <div class="row" style="position: relative;margin-bottom: 30px;"> <div>{{i}}</div> <div class="workSeriesThumbnailStrip"> {% for obj in object_list %} {% if obj.collection == i %} <script> var level = level+1; </script> <a href="{{ obj.get_absolute_url }}"><img src="{{ obj.image.url }}" style="float:left;width:67px;height:87px;margin:10px;" ></a> {% endif %} {% endfor %} </div> <script> document.write(level); </script> </div> {% endfor %} <script> if ($('.workSeriesThumbnailStrip').is(':empty')) { $('.row').remove(); } </script> {% endwith %} </div> <div class="clear"></div> {% endblock content %} -
Not able to list the directory or change Directory on FTPS server using Python
I have created a program (ImplicitTLS.py) to connect to FTPS server by referring this link Python FTP implicit TLS connection issue and another program to where i'm giving the credentials with respective to "ImplicitTLS.py". why the code doesn't able to list the directory or change directoty? And also i wanted to upload CSV files into this FTPS_DIR on ftps server 1.ImplicitTLS.py : import ftplib, socket, ssl FTPTLS_OBJ = ftplib.FTP_TLS # Class to manage implicit FTP over TLS connections, with passive transfer mode # - Important note: # If you connect to a VSFTPD server, check that the vsftpd.conf file contains # the property require_ssl_reuse=NO class FTPTLS(FTPTLS_OBJ): host = "127.0.0.1" port = 990 user = "anonymous" timeout = 60 logLevel = 0 # Init both this and super def __init__(self, host=None, user=None, passwd=None, acct=None, keyfile=None, certfile=None, context=None, timeout=60): FTPTLS_OBJ.__init__(self, host, user, passwd, acct, keyfile, certfile, context, timeout) # Custom function: Open a new FTPS session (both connection & login) def openSession(self, host="127.0.0.1", port=990, user="anonymous", password=None, timeout=60): self.user = user # connect() ret = self.connect(host, port, timeout) # prot_p(): Set up secure data connection. try: ret = self.prot_p() if (self.logLevel > 1): self._log("INFO - FTPS prot_p() done: " + ret) except Exception … -
Django: three models in inline formest factory
I have this code that wors perfectly: I have two related models that I figure out with a inline formest factory. The models are two: Lavorazione and Costi_materiale: models.py class Lavorazione(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali) numero_lavorazione=models.IntegerField('Nr. Lavorazione') class Costi_materiale(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, e) numero_lavorazione=models.ForeignKey(Lavorazione,) quantita=models.DecimalField() I have created a inline formset facotory: CostiMaterialeFormSet = inlineformset_factory( Lavorazione, Costi_materiale, form=CostiMaterialeForm, fields="__all__", can_delete=True, extra=1 ) And the following viwes.py: class CostiCreate(CreateView): model = Lavorazione template_name = 'commesse/costi_create.html' fields= '__all__' success_url = reverse_lazy('costi_add') def get_context_data(self, **kwargs): data = super(CostiCreate, self).get_context_data(**kwargs) if self.request.POST: data['costs'] = CostiMaterialeFormSet(self.request.POST) else: data['costs'] = CostiMaterialeFormSet() return data def form_valid(self, form): context = self.get_context_data() costs = context['costs'] with transaction.atomic(): self.object = form.save() if costs.is_valid(): costs.instance = self.object costs.save() return super(CostiCreate, self).form_valid(form) But, If I wanto to insert a third models, named Mod class Mod(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali) numero_lavorazione=models.ForeignKey(Lavorazione) nome_cognome=models.CharField() That have the same foreingkey of Costi_materiale with the models Lavorazioni???I have tried but the code does not work. Help me! -
Handle many ViewSets with one URL in the Django rest framework?
What I want is to handle three ViewSet with one URL respect to the provided request.data. Let's make it more clear by diving into code: Here is my router.py # vim: ts=4 sw=4 et from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from . import viewsets router = DefaultRouter() router.register(r'endpoint', viewsets.MyViewSet, 'my-viewset') notification_urls = [ url(r'^', include(router.urls)), ] Question1: Is it possible to handle three ViewSet with one URL? For example, according to the data that has been sent, I want to select dynamically a different ViewSet instead of assigned MyViewSet. ---> /endpoint/ ---- | request.data['platform'] == 1 ----> ViewSet1 | request.data['platform'] == 2 ----> ViewSet2 | request.data['platform'] == 3 ----> ViewSet3 and I know that I can call other ViewSet's methods in a MyViewSet something like this Question but this is really a messy one. Question2: Is it possible to dynamically pass extra params respect to the data that has been sent to a ViewSet? For example, according to the data that has been sent, I want to pass an extra param into MyViewSet. I know that I can do all this stuff in ViewSet initial method, Like this: def initial(self, request, *args, **kwargs): self.set_platform() super(NotificationViewSet, self).initial(request, *args, … -
How to use 'self' in background task function in Django?
I have a Django project and I have used django-background-tasks library for my background processes. I have created a class for this background task and my bgtask function is in that class. I wanna use 'self' in that function but i got an error such as missing 1 required positional argument: 'self' My code is such as below; class Progress: def __init__(self): self.progress = 0 self.increase(5) @background() def increase(self, num): for i in range(num): self.progress += 8 How can i fix this error?