Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Overriding save method to send data
I'm working on human management system where a user applies for leave and the respected data should get into the history table only when the status == '0' I've tried with signals but every time when admin saves, it's getting registered into the table. I've read that, it's better to override save() rather use signals STATUS_CHOICES = (('0', 'Rejected'),('1', 'Accepted'),) class Employee(models.Model): employee_ID = models.CharField(max_length = 20) name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) status = models.CharField(max_length = 15, choices = STATUS_CHOICES) def save(self, *args, **kwargs): leave = Employee() if Leave.status == '1': history = History() history.employee_ID = leave.employee_ID history.name = leave.name history.save() print('data sent') class History(models.Model): name = models.CharField(max_length = 50) employee_ID = models.CharField(max_length = 20) What's the mistake I've been doing while overriding the save method? -
Convention: Protected vs private
I have the following calculation in my models.py. Is it correct I choose two __ or should I rather use _ to just make it protected, but not private? def __calc_tax(self): return self.total_gross - (self.total_gross / (1 + self.tax_percentage)) # Quantititze ! def save(self, *args, **kwargs): if self.ticket_tax: self.total_tax = self.__calc_tax() return super().save(*args, **kwargs) -
restrict access to other pages except home page in Django
I am developing a Django application. This application has a lot of functionality. So I broke down each functionality into sub-functionality and implemented in each individual app. And I used ajax, javascript to display the result in my home page when the form is submitted instead of redirect to my sub-functionality app page. But the user can access the sub-functionality app page through URL. I want to restrict the user from accessing the sub-functionality app page in this way. Here let me explain with one of my sub-functionality the calculator My main page has the template and all the forms in it for each sub-functionality. So one of the sub-functionality is a calculator calculator view def index(request): calculated_result = do_calculation(request) # claculation logic return JsonResponse(calculated_result) claculator urls app_name = 'calculator' urlpatterns = [ url(r'^$', views.index, name='calculator'), ] my javascript code for getting information from the calculator URL and display it on my home URL $(document).ready(function(){ $('#calc_form').submit(function(event){ console.log(event); event.preventDefault() $.ajax({ url:'/calculator/', type:'POST', data:$(this).serialize(), success:function(response){ $('#output_box').html(`${response.result}`); } }); }) }) When the user submits the form on the main page, the control goes to the calculator view performs the calculation and displays it in calculator URL, but my js script blocks the … -
Change Default Value of Slug_Field to customslug in Django
I am using Generic Views in Django 2.1. My views get mixed because I don't know why: urls.py: path('study-abroad/<slug:slug>/', views.SubjectDetailView.as_view(), name='subject-detail'), path('study-abroad/<slug:slug>/', views.StudylevelDetailView.as_view(), name='studylevel-list'), So I think it is better to name custom slugs in order to prevent that. Like this: urls.py: path('study-abroad/<slug:subjectslug>/', views.SubjectDetailView.as_view(), name='subject-detail'), path('study-abroad/<slug:studylevelslug>/', views.StudylevelDetailView.as_view(), name='studylevel-list'), My Question is: How can I change the default value of Slug_Field to mycustomslug? (It is slug by default in Django) Views.py class SubjectDetailView(generic.DetailView): model = Programmesearch template_name = 'mnsdirectory/subject_detail.html' def slugify(value, allow_unicode=False): slug_field = slugify('Programmesearch.full_subject_name') class StudylevelDetailView(generic.DetailView): model = StudyLevel template_name = 'mnsdirectory/study_level.html' def slugify(value, allow_unicode=False): slug_field = slugify('StudyLevel.study_level') Models.py: class Programmesearch(models.Model): subject_name = models.CharField(max_length=100, choices=SUBJECT_NAME_CHOICE) subjectslug = models.SlugField(unique=True) def __str__(self): return self.subjectslug def get_absolute_url(self): return reverse('SubjectDetailView', args=[str(self.id)]) class StudyLevel(models.Model): title = models.CharField(max_length=100, blank=True, null=False) studylevelslug = models.SlugField(unique=True) def __str__(self): return self.studylevelslug def get_absolute_url(self): return reverse('StudylevelDetailView', args=[str(self.id)]) -
Passing errors to redirected template in views.py in django
I am using try except to handle errors in views.py. In the exception area i want to redirect user to a template if there is an error. While redirecting to the template, i want to pass errors to template and show errors at the beginning of that page. try: car.delete() except ProtectedError, e: return redirect(reverse('car-operations') + '?car_no=' + str(car.car_no), {'errors': e}) The ProtectError occurs when i try to delet the car. But this error is not passed to redirected page. In redicreted page i use below code to show errors. {% if errors %}<div class="alert alert-danger">{{ errors }}</div>{% endif %} I see that error occurs. But i couldn't pass it to template. If i use render request, i can pass the error to template but this time i can't call the template with "'?car_no=' + str(car.car_no)" -
Django - passing data with 'include'
I'm a newbie in Django and here's what I want to do: I want to have a base.html that includes a Navigation. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Penis</title> </head> <body> {% include 'nav.html' %} {% block content %}{% endblock %} </body> </html> pretty simple, but: The navigation should render it's own content flexible, as i want to add a cms later. <nav class="nav"> {% for item in sites %} <a class="nav__item" href="{{ item.href.value }}">{{ item.label }}</a> {% endfor %} </nav> I have a render method of index.html (which just extends base.html and adds an h1 tag for testing purposes) like so def home_view(request, *args, **kwargs): opts = { 'sites': [ { 'href': { 'value': '/someurl' }, 'label': 'Some Label' }, { 'href': { 'value': '/lorem' }, 'label': 'Lorem Ipsum' }, { 'href': { 'value': '/contact' }, 'label': 'Contakt' } ] } return render(request, 'index.html', opts) but if I run my local server my content does not get passed. -
problem in creating a class view for creating new object in django
im trying to create a view class for handling creation of new Person object. you may access my code on Github via this link: https://github.com/DAkbari/FaceRecognitionDjangoWebApi this is definition of Person object class Person(models.Model): firstName = models.CharField(max_length=200) lastName = models.CharField(max_length=200) faceEncode = models.CharField(max_length=3000) facePicture = models.FileField() lastLoginPicture = models.FileField() code = models.CharField(max_length=100) i created class "UserForm" in forms.py in order to show fields which are required for creation of new Person objec: from identify.models import Person from django import forms class UserForm(forms.ModelForm): class Meta: model = Person fields = ['firstName', 'lastName', 'code', 'facePicture'] in next step i created a view for UserForm: class PersonCreate(View): form_class = UserForm template_name = 'identify/new_person_form.html' #display a blink form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # process form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) # clean normalized data facePicture = form.cleaned_data['username'] FName = form.cleaned_data['firstName'] LName = form.cleaned_data['lastName'] code = form.cleaned_data['code'] user.save() after navigating to resulting view and entering required fields when i click submit button the file which i've selected disappears and form raises required error for that field: if i remove facePicture field from forms.UserForm everything would be fine -
Mysql database Configuration for Django
I have installed mysql and it is in running state.. In my Django Project I have configured django like this Setting.py DATABASES = { 'default': { 'NAME': 'SMM_DB', 'ENGINE': 'mysql.connector.django', 'USER': <user>, 'PASSWORD': <password>, 'OPTIONS': { 'autocommit': True, }, } } On executing this command"python manage.py migrate" , got the following error Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 337, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 4, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/base_user.py", line 52, in class AbstractBaseUser(models.Model): File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 124, in new new_class.add_to_class('_meta', Options(meta, app_label)) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 330, in add_to_class value.contribute_to_class(cls, name) File "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/usr/local/lib/python2.7/dist-packages/django/db/init.py", line 33, in getattr return getattr(connections[DEFAULT_DB_ALIAS], item) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 212, in getitem conn = backend.DatabaseWrapper(db, alias) File "/usr/lib/python2.7/dist-packages/mysql/connector/django/base.py", line 336, in init super(DatabaseWrapper, self).init(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 96, in init self.client = self.client_class(self) TypeError: Error when calling the metaclass bases 'NoneType' object is not callable -
How to set related_name in ManyToMany field in an abstract model?
I have this abstract model: class HasSystemMessage(models.Model): class Meta: abstract = True messages = models.ManyToManyField(SystemMessage, related_name=?) I am going to use this abstract model in at least three other models, lets say, A, B, and C. How can I set the related_name dynamically for these classes? for example, for class B, I want the related_name to be Bs. Is it possible to do so? -
How to filter model results for multiple values dynamically in django
I have following course model with professor, code, semester_season, semester_year, etc I have request post values: coursecode = request.POST['coursecode'] courselist = request.POST['courselist'] semesteryear = request.POST['semesteryear'] semesterseason = request.POST['semesterseason'] this is my filter a queryset for finding above post values: course_listobj = Course.objects.filter(code=coursecode, title=courselist, semester_year=semesteryear, semester_season=semesterseasonid).order_by('code', 'title', 'semester_year', 'semester_season') This is my front end: how can find if one post value is empty find other values in query set dynamically i mean if no post value means coursecode = None here i am finding like below: if (coursecode != 'None') and (courselist == 'None' and semesteryear == 'None' and semesterseason == 'None'): course_listobj = Course.objects.filter(code=coursecode).order_by('code') like above multiple if conditions are required. pls suggest me any one how can i do one query with multiple conditions. Thanks in advance ... -
accessing media file in django
i have this root project polls data xml_files x.xml i have added MEDIA_URL = '/data/' MEDIA_ROOT = '/data/xml_files/' and i have added urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('web.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) when i localhost:8000/data/fuzzy.xml it sends 404 page not found with "/data/xml_files/FuzzyMirab1.xml" does not exist how can i access that? -
How to disable custom dates in datepicker?
I'm working on a django project, where the user need to pick the dates for applying leaves. So, I have included the below code in my base.html. I have no basic knowledge in javascript but some how i came up how to disable weekends. <script> $(document).ready(function() { $('.datepicker').datepicker( { minDate : 0, beforeShowDay : $.datepicker.noWeekends } ); }); </script> I have list of custom dates which are declared as holidays and I want them to be disabled in the datepicker -
Django Getting m2m fields old and new value in save
I have a model that where I want to keep track of the changes whenever the fields have been updated/edited. So every time before I save the new update, I will get the old and new values and create a new Audit object to keep track those changes. Tried the method below which works for most fields except m2m relationship fields (such as User) where it both the old and new values remain the same. Are there anyway I could get the old and new m2m field values so that I can create a record of Audit every time the Model object is saved/updated? def __init__(self, *args, **kwargs): super(Model, self).__init__(*args, **kwargs) self.old_name= self.name self.assigned_users = self.assigned_users.all() def save(self, *args, **kwargs): audit = audit.objects.create( old_name=self.old_name, new_name=self.name. old_assigned_users=self.old_assigned_users, new_assigned_users=self.assigned_users.all()) super(Model, self).save(*args, **kwargs) -
Read only models and displayed as a list in django admin?
I want to display a model from db onto my django admin. What I want do with it is just simply display the details, no editing. is there a way to somehow "disable" the CRUD functions of a model in the django admin ? I can't seem to find a way. my current django version is 2.1.1. thanks for the help! -
Is a Django/React/WebGL a bad stack for web based game with community features around it?
I have started a project for my own education (and profit if it becomes a viable product), which is a web based strategy game. I am building all the server side game logic in python, and I am planning on learning Django and React to use in the front end, with WebGL for the actual game graphics. The reason I want to use a large framework like Django is because I plan on building a community around the game with forums and chat for people to share strategies, etc. There will also be leader boards and that kind of thing as well, so I need something that will be able to handle security and other things. The game will be 3D but it's turn based so the network connection to the server side game engine isn't super critical. Nevertheless, I am wondering if passing my game events to the server through Django is a bad idea. Could anyone with more experience with this stack enlighten me? -
Sharing a large pandas dataframe across requests in Django
I am building an application where users will select a certain set of filters, make a request to a Django back end, and the client will build an interactive plot of the returned filtered data. Instead of making queries to the DB for every request, I want to load the whole data in-memory once when the server is first run and apply the filters directly on it and return a subset of the data to the client. My first thought is to simply load the data in a custom class's init function and have this class's methods handle filtering and reformatting the data for the client. My question is: is this approach safe? What are some potential issues I can encounter? Is the time I'm going to save from not making DB queries for each request worth it? -
django : How to use signals?
After creating an user account with this model class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) the form class UserCreateForm(UserCreationForm): class Meta: fields = ("first_name", "last_name", "username", "email", "password1", "password2") model = get_user_model() I want an default entry into another model from another application yet in the same project class History(models.Model): name = models.CharField(max_length = 50) employee_ID = models.CharField(max_length = 20) earned_leave = models.IntegerField(default = 10) casual_leave = models.IntegerField(default = 10) sick_leave = models.IntegerField(default = 10) paid_leave =models.IntegerField(default = 10) where employee_ID is the username and name is the first_name. I have tried using signal but I have no idea how to send the values into db. def send_data(sender, instance, created, **kwargs): print('data sent') post_save.connect(receiver = send_data, sender= User) Instead of this print statement what should I write in order to send the code into History table in db. I'm working on human management system. -
Access View variables at the Model level
I need to call an utility/function every time after a Model is saved/updated, so I overwrite the save at the Model level(do this for multiple Models). def save(self, *args, **kwargs): if self.adding: tp=created_at else: tp=updated_at if self.is_active: act=1 ..... super().save(*args, **kwargs) create_note(tp=tp, act=act, target_object=self)) My issues is that I need to access also some variable that I set at the level of the View, but are not sent to the Model. I do also some checks/operations with the Model attributes value, and send them as the utility arguments. Otherwise I need to query the database again 2-3 times. It is possible to get the variables from View at the Model level, even if they are not part of the Model ? -
Saving a rendered pdf file to model field Django
I'm trying to save a pdf file which is rendered using HTML to a model field right now, it throws this error. coercing to Unicode: need string or buffer, instance found this is the code def save_to_pdf(template_src, context_dict, pk): import ipdb; ipdb.set_trace() instance = get_object_or_404( Project.objects.filter(pk=pk, is_deleted=False)) template = get_template(template_src) context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result,link_callback=fetch_resources) pdfnew=file(pdf) instance.structural_info.save('structure.pdf',pdfnew) return True structural_info is the file field. What is the correct way to do it? -
Download/Export a list view in excel format
I am trying to save some data from DB as excel format. But this gives me data of only one table. class MyView(ListAPIView): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="QaData.xlsx"' wb = Workbook() ws = wb.active rows = MyModelClass.objects.all().values_list(*data_set).order_by('id') for row in rows: row_num += 1 ws.append(data_row) wb.save(response) return response I need to save my data as it shown in my list view (which includes data of several tables). is it possible to get as rows = (my list view rows) this is how i get data to show in my list view return ListAPIView.get(self, request, args, kwargs) I cannot figure out how to convert this result to a array (or to json). Any help would be appreciate. -
Django jet google analytics API request failed
Successfully setup django-jet and everything working. But after few hours google analytics data is not showing. And displaying API request failed. Using django 2.0(django 2.1 has compatibility issue) with latest django-jet, google-analytics api 1.4.1 -
How to combine fields from different Models in one form in Django?
Let's say I have 3 models class Products(models.Model): Brand= models.ForeignKey(City,models.CASCADE, related_name='city') Title = models.CharField(max_length=200, db_index=True) description = models.TextField(blank=True,max_length=250) price = models.DecimalField(max_digits=11, decimal_places=2) class Clothes(models.Model): product = models.ForeignKey(Products,models.CASCADE, related_name='clothe') Color= models.CharField(max_length=200, db_index=True, unique=True) class Smartphones(models.Model): product = models.ForeignKey(Products,models.CASCADE, related_name='phone') storage= models.DecimalField(max_digits=11, db_index=True) how can I combine fields from different models in one form so we can have something like this: class ClothesForm(ModelForm): class Meta: model = Clothes fields = ('brand','Title','Color) class PhonessForm(ModelForm): class Meta: model = Smartphones fields = ('brand','Title','storage') if it work is it possible to assign brand choise for each form, for example: phones_Brand = (('Samsung','Samsung'), ('Iphon','Iphon')) clothes_Brand = (('Nike','Nike'), ('Adidas','Adidas')) Thank you -
Uncaught TypeError: svg.append(...).attr(...).selectAll(...).data(...).enter is not a function
I am trying to recreate the force directed graph demonstrated by Bostock in this example https://bl.ocks.org/mbostock/4062045 with the dataset that I have. I am parsing the JSON formatted data using Django serializers and have the data available on the URL specified in my D3.js code. I am using D3 v4. <style> .links line { stroke: #999; stroke-opacity: 0.6; } .nodes circle { stroke: #fff; stroke-width: 1.5px; } </style> <svg width="960" height="600"></svg> <script src="https://d3js.org/d3.v4.min.js"></script> <script> var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg.attr("height"); var color = d3.scaleOrdinal(d3.schemeCategory20); var simulation = d3.forceSimulation() .force("link", d3.forceLink().id(function(d) { return d.se_id; })) .force("charge", d3.forceManyBody()) .force("center", d3.forceCenter(width / 2, height / 2)); d3.json("../forceLink", function(error, graph) { if (error) throw error; var link = svg.append("g") .attr("class", "links") .selectAll("line") .data(graph.links) .enter() .append("line") .attr("stroke-width", function(d) { return Math.sqrt(d.value); }); var node = svg.append("g") .attr("class", "nodes") .selectAll("circle") .data(graph.nodes) .enter().append("circle") .attr("r", 5) .attr("fill", function(d) { return color(d.group); }) .call(d3.drag() .on("start", dragstarted) .on("drag", dragged) .on("end", dragended)); node.append("title") .text(function(d) { return d.se_id; }); simulation .nodes(graph.nodes) .on("tick", ticked); simulation.force("link") .links(graph.links); function ticked() { link .attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node .attr("cx", function(d) { return … -
Image upload goes to "None" folder in django
I'm trying to upload an image via ajax. The image uploads well, but it is delivered inside a "None" folder, between the MEDIA_ROOT value and upload_to parameter of ImageField. My current settings are as follows: MEDIA_ROOT = 'static' Inside my app's models.py: image = models.ImageField(blank=True, null=True, upload_to='img/devices') When I upload the image, it goes to static/None/img/devices, instead of static/img/devices The form is as follows: class DeviceForm(ModelForm): class Meta: model = Device fields = ['name', 'model', 'serial', 'location', 'note', 'image', 'page', 'address'] And the saving snippet: if request.method == 'POST': post_data = request.POST.dict() form = DeviceForm(post_data, request.FILES) if not form.is_valid(): return JsonResponse({"message": "Form is invalid"}, status=400) obj = form.save() return JsonResponse(obj.to_dict(), safe=False) Is there a configuration that I'm missing? Any help would be appreciated -
Many to Many relationship Django
I have 2 Tables in my Postgres DB. One contains multiple states from different part of the World and the other one contains postal code that are in those states. They're multiple postal code in one city. But postal code are only link to a single city. Here an example of my 2 tables : States : +----+------------+-----------+-----------------------+ | pk | state | city | city_id | +----+------------+-----------+-----------------------+ | 1 | Montreal | Quebec | 123 | +----+------------+-----------+-----------------------+ | 2 | Laval | Quebec | 123 | +----+------------+-----------+-----------------------+ | 3 | Ottawa | Ontario | 837 | +----+------------+-----------+-----------------------+ Postal Code : +----+------------+-----------+-----------------------+ | pk |Postal Code | city | city_id | +----+------------+-----------+-----------------------+ | 1 | H1H1H1 | Quebec | 123 | +----+------------+-----------+-----------------------+ | 2 | H4P2T5 | Quebec | 123 | +----+------------+-----------+-----------------------+ | 3 | G1G2G2 | Ontario | 837 | +----+------------+-----------+-----------------------+ I am using django autocomplete-light for my input and now I want to Forward my states to filter my Postal Code with the city_id field. The problem that I have is that Django errors tell me : 'state.pk' must set unique=True because it is referenced by a foreign key. when I try to create a one to many …