Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Building a form from three models in Django - need some minor tweaks
I am currently having three models linked together, but the main model is Lecture. I wanted to allow the user to add lectures data to my models. The thing is that the user needs to be able to add lectures only for a course, but to able to upload many files to the lecture. What I tried is this: def classroom(request): if request.method == 'POST': form = LectureForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = LectureForm() context = { 'form': form } return render(request, 'courses/classroom.html', context) class LectureForm(forms.ModelForm): course = forms.ModelChoiceField(queryset=Course.objects.all()) lecture_category = forms.ChoiceField(choices=LECTURE_CHOICES) lecture_title = forms.CharField(max_length=100, required=True) content = forms.Textarea() files = forms.FileField(queryset=FileUpload) class Meta: model = Lecture fields = ('course', ' lecture_category', 'lecture_title', 'content', 'files') class Course(models.Model): name = models.CharField(max_length=50, unique=True) class Lecture(models.Model): LECTURE_CHOICES = ( ('Courses', 'Courses'), ('Seminars', 'Seminars'), ) course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures') lecture_category = models.CharField(max_length=10, choices=LECTURE_CHOICES, default='Courses') lecture_title = models.CharField(max_length=100) content = models.TextField() class FileUpload(models.Model): files = models.FileField(upload_to='documents', null=True, blank=True) lecture = models.ForeignKey('Lecture', related_name='files', on_delete=None, default=None) But I get following errors: Unknown field(s) ( lecture_category) specified for Lecture. I also do not know how to bind properly FileUpload and Course to the form. Little advice ? -
Don't know how to change the background photo of bootstrapping template
I am learning the django framework and using bootstrap as my frontend. I tried to use the bootstrap theme (https://startbootstrap.com/template-overviews/creative/) However, I cannot find where to replace the background photo of the first page. I cannot locate where is the 'scr img=' code in the html file. Can anyone advise. Thanks. -
Response returned before save complete django
There are two calls that happen back to back on client side: Create the order, return the order id Charge the customer, pass the order id The order model is fairly large and calls Order.save() a couple times during the first call. However, the response from (1) is returned before the saving has finished because the wrong price is charged to the customer. Basically, the order price gets updated once the drink price and modifier price gets calculated and the response is returned after the drink price is calculated but does not wait for the modifier price. I have narrowed down the logic to here: def create(self, request): ... self.perform_create(serializer, request, drinks, foods) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) ... def perform_create(self, serializer, request, drinks, foods): serializer.save(drinks=drinks, foods=foods) ... def save(self, *args, **kwargs): ... super(Order, self).save(*args, **kwargs) ... def customerdrinkorder_presave(sender, instance, **kwargs): """ custom pre_save processes of :model:'drinks.CustomerDrinkOrder' """ try: milk_price = instance.milk.price except AttributeError: milk_price = Decimal(0) instance.price = instance.quantity * (instance.customer_drink.store_drink.price + milk_price) def customerdrinkorder_postsave(sender, instance, created, **kwargs): """ custom post_save processes of :model:'drinks.CustomerDrinkOrder' """ order = instance.order print("LIMES1") update_order_total(order) def customerdrinkmodifier_presave(sender, instance, **kwargs): """ custom pre_save processes of :model:'drinks.CustomerDrinkModifier' """ instance.price = instance.quantity * instance.modifier.price def … -
Django doesn't check for a csrf token with Ajax post
According to the Django docs, Django should have csrf token validation enabled by default, using a middleware. When I look in my settings file I indeed see the middleware being included. However, when I do a post request without a csrf token using Ajax, Django will just allow it. Should it not return an error saying the csrf token is invalid? I am seeing a lot of questions from people who can't get their csrf token validated, but I can't get it INvalidated. This is my Ajax post function (I collect the data from my inputs with js, and pass it to this function): function ajaxPost(url, data, success) { fetch(url, { method: 'POST', // or 'PUT' body: JSON.stringify(data), headers: new Headers({ 'Content-Type': 'application/json' }) }).then(res => res.json()) .then(response => { if (response.status !== success) { //errors } updateView(response); }) .catch(error => console.error('Error:', error)) } And this is my view function: @api_view(['POST']) # API endpoint for posting bulk properties def bulk(request): new_properties = [] if request.method == 'POST': for obj in request.data: discipline = Discipline.objects.get(pk=obj['discipline.id']) root_function = Function.objects.get(pk=obj['root_function']) new_property = Property(name=obj['name'], value=obj['value'], unit=obj['unit'], discipline_id=discipline) new_property.save() new_property.function.add(root_function) new_properties.append(new_property) new_properties = json.loads(serializers.serialize('json', new_properties)) return JsonResponse({'status': 201, 'new_properties': new_properties}) -
Django - Sqlite Database
Any help is greatly appreciated. I am using Django and SQLite, I am trying to join the auto generated auth_user table with an input table that I have created using a model. Models.py; class Input(models.Model): height = models.IntegerField(default=0) waist = models.IntegerField(default=0) bust = models.IntegerField(default=0) hips = models.IntegerField(default=0) class Meta: db_table = "Project_input" The purpose of joining the tables is so that when a user logs in the information they enter into my input table is only associated with them. I understand that I have to add a foreign key to this model! But how do I reference the auth_user table? -
Position absolute for <img/> when using xhtml2pdf (Django)?
Can I generate PDF with CSS position: absolute; for <img src="..."/> html tag? I need to place handwritten signature and company stamp (PNG files) to bottom of order voucher. Something like this: -
'User' object has no attribute 'backend' using Python 3.5 and Django 1.8
I am making a project using python 3.5 and Django 1.8 ,there is a feature for login and signup, so login and signup are two different apps THIS image shows my directory structure of apps Now in login app's form , I import from signup.models allusers1 (a class in signup.models) Using view I pass the form .and when I enter the credentials in the database eg checkit and 12345 (username and password) ,I get this error AttributeError at /login/ 'User' object has no attribute 'backend' This is login/forms.py from django import forms from signup.models import allusers1 from django.contrib.auth import ( authenticate, login, logout, get_user_model, ) User=get_user_model() class UserLoginForm(forms.ModelForm): class Meta: model = allusers1 fields=['username','password'] widgets = { 'password': forms.PasswordInput(), } def clean(self ,*args,**kwargs): username=self.cleaned_data.get("username") password=self.cleaned_data.get("password") user_qs = User.objects.filter(username=username) if user_qs.count() == 0: raise forms.ValidationError("The user does not exist") else: if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("Incorrect password") if not user.is_active: raise forms.ValidationError("This user is no longer active") return super(UserLoginForm,self).clean(*args,**kwargs) This is signup/models.py from django.db import models from django import forms # Create your models here. class allusers1(models.Model): username=models.CharField(max_length=40) password=models.CharField(max_length=40) phoneno=models.CharField(max_length=10,primary_key=True) otp=models.IntegerField(blank=True,null=True,default=0000) def __str__(self): return self.username login/views.py from django.shortcuts import render,redirect from .forms import UserLoginForm … -
Django single website structure
I want to start a new django project. This will just be a relatively simple website to test django itself. So the way all tutorials structure their project is this: mysite mysite some_app ... For me it's not very clear what does what. I don't really need any app right now. Could I implement my website without using any app? Should I use an app? What would it be called for a simple website? -
AttributeError: 'unicode' object has no attribute 'create_connection' in Django Push Notification
In my project, I am using django-push-notifications for sending push notification to mobile devices. But I am getting following error. [2018-02-22 13:41:20,881: ERROR/ForkPoolWorker-1] Task ballogyApi.tasks.notification_tasks.send_notification_task[e6a5984a-d3b9-4570-a24e-be61702ca4e5] raised unexpected: AttributeError("'unicode' object has no attribute 'create_connection'",) Traceback (most recent call last): File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/celery/app/trace.py", line 374, in trace_task R = retval = fun(*args, **kwargs) File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/celery/app/trace.py", line 629, in __protected_call__ return self.run(*args, **kwargs) File "/home/hassan/Project/ballogy/ballogyApi/tasks/notification_tasks.py", line 41, in send_notification_task data=data File "/home/hassan/Project/ballogy/ballogyApi/tasks/notification_tasks.py", line 16, in send_notification android_response_function, ios_response_function, bulk, **data) File "/home/hassan/Project/ballogy/ballogyApi/utils/notification_utils.py", line 37, in perform_notification_process to_user, android_response_function, ios_response_function, bulk, **kwargs) File "/home/hassan/Project/ballogy/ballogyApi/utils/notification_utils.py", line 47, in send_notification_to_user to_user, android_response_function, ios_response_function, *args, **kwargs) File "/home/hassan/Project/ballogy/ballogyApi/utils/notification_utils.py", line 90, in send_single_notification badge=not_count + total_requests) File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/push_notifications/models.py", line 167, in send_message **kwargs File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/push_notifications/apns.py", line 113, in apns_send_message certfile=certfile, **kwargs File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/push_notifications/apns.py", line 66, in _apns_send client = _apns_create_socket(certfile=certfile, application_id=application_id) File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/push_notifications/apns.py", line 38, in _apns_create_socket use_alternative_port=get_manager().get_apns_use_alternative_port(application_id) File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/apns2/client.py", line 39, in __init__ self._init_connection(use_sandbox, use_alternative_port, proto) File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/apns2/client.py", line 48, in _init_connection self._connection = self.__credentials.create_connection(server, port, AttributeError: 'unicode' object has no attribute 'create_connection' Kindy help me solving this issue. -
Django: User.object.get() logs user in
I am just a beginner in Django but I have come across very interesting problem. I am not logged in on my webpage, but after I want to see someone's profile it automatically logs me in that user. It seems like a huge security hole. I also put print statement in and it says that user is authenticated. Answers will be appreciated. views.py def login_view(request): form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) return render(request, "home/login.html", {'form': form}) def user_feedView(request, username): try: userU = User.objects.get(username=username) print(userU.is_authenticated) except User.DoesNotExist: raise Http404("User does not exist") return render(request, 'home/user_feed.html', {'user': userU}) urls.py urlpatterns = [ path('user/<username>/', views.user_feedView, name='username'), path('logout/', views.logout_view, name='logout'), path('login/', views.login_view, name='login'), path('', views.index, name='home') ] -
Setting up django with celery,
I am trying to set up celery with django on my development server, running on windows. Following are changes i made. I followed steps by this link http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html Filestructure Noisebox -Noisebox --__init__.py --celery.py --settings -rehearsalbooking --tasks.py init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'noisebox.settings') app = Celery('noisebox') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py from celery import shared_task from .models import Room from django.utils import timezone @shared_task def calculate_timeslots(room_id): room = Room.objects.get(id=room_id) room.create_timeslots_until_license_expires(timezone.now()) return True When i run the task, the task gets sent to the celery server, but is not executed. (noisebox-env) C:\Users\jonas>celery worker -------------- celery@DESKTOP-MH2SD2S v4.1.0 (latentcall) ---- **** ----- --- * *** * -- Windows-10-10.0.16299-SP0 2018-02-22 14:22:38 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: default:0x29efc50 (.default.Loader) - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [2018-02-22 14:22:39,439: ERROR/MainProcess] Received unregistered task of type … -
Django mapping tables - concatenate?
ive seen a few questions on here sort of similar but none that assist me in creating what I actually need. Im using Django 1.11 and I have some mapping tables as an example below, where the site and circuit values are foreign IDs id | site | circuit ------------------- 1 | 1 | 1 2 | 1 | 11 3 | 2 | 4 4 | 3 | 6 5 | 2 | 1 so from the data above I can see circuit 1 is used on site 1 and site 2. so I would like a query that will show site | circuit -------------- 1,2 | 1 1 | 11 2 | 4 ... I found the this How to concat two columns of table django model but it seems to concat on a set string? where as I need to concat on site_id where circuit_id is the same can anyone assist with this, these sorts of functions are beyond my skill level. Thanks -
Django does not seem to account for DayLightSavings
In my models I want to update the last_edited value of the Submission object everytime the UserAnwser object is saved. To this end I've written the following code from django.utils import timezone ... class UserAnswer(models.Model): answer = models.FloatField() question = models.ForeignKey(Question, related_name='answers') submission = models.ForeignKey(AssessmentSubmission, related_name='answers') #Update submission.last_edited on answer. def save(self, *args, **kwargs): submission = self.submission submission.last_edited = timezone.now submission.save() super(UserAnswer, self).save(*args, **kwargs) I've set the correct timezone in the settings.py file: LANGUAGE_CODE = 'nl' TIME_ZONE = 'Europe/Amsterdam' USE_I18N = True USE_L10N = True USE_TZ = True However, everytime I change the answer and lookup the submission.last_edited value in our django-rest api, the time is 1 hour behind the actual time. Its almost as if the time is being displayed in 'summer time' and the DST is not handled correctly. For example, if I edit an answer at 13:30, our api will return 12:30 Since the settings.TIMEZONE has been set and I am using django's django.utils timezone object its not clear to me what I doing wrong, could someone point me towards the right direction? -
Django test error arguments 0 given
I'm having trouble running this function: def test_custom_mail_server_connection(host, port, user, password, use_tls, recipient): ''' Test connection of mailing server with given user params returns None if mail is sent successfully, a string containg the error otherwise ''' result = None message_list = [] tenant = get_tenant_by_schema_name(connection.schema_name) # create new mail_connection mail_connection = mail.get_connection() mail_connection.host = host mail_connection.port = port mail_connection.username = user mail_connection.password = password mail_connection.use_tls = use_tls from_email = '%s <%s>' % (tenant.name, mail_connection.username) subject = _(u'%(name)s: SMARTFENSE - Prueba de servidor de correo propio') % {'name': tenant.name} mail_content = SimpleTemplateResponse("emails/email_server_test.html", { 'host': host, 'port': port, 'user': user, 'use_tls': use_tls, }, content_type="text/html", charset="utf-8").render().content msg = mail.EmailMessage( subject, mail_content, from_email, [recipient] ) msg.content_subtype = 'html' message_list.append(msg) try: mail_connection.open() mail_connection.send_messages(message_list) except Exception as e: result = "%s" % e finally: mail_connection.close() set_mail_connection_config(mail_connection, 'default') return result That basically checks if a given mail host is right in order to use it. I wrote this test: def test_test_custom_mail_server_connection(self): result = test_custom_mail_server_connection('smtp.gmail.com', 587, 'xxxxx@gmail.com', 'xxxxxxx', True, []) self.assertEqual(result, None) And I'm getting the next error: ERROR: Test connection of mailing server with given user params ---------------------------------------------------------------------- Traceback (most recent call last): File "/Volumes/Datos/Diamo/Smartfense/env/lib/python2.7/site-packages/nose/case.py", line 197, in runTest self.test(*self.arg) File "/Volumes/Datos/Diamo/Smartfense/env/lib/python2.7/site-packages/nose/util.py", line 620, in newfunc … -
How do I pass the request object to the method_decorator in django class views?
I have been working on this all day. I am trying to write custom permission for class views to check if user is in a certain group of permissions. def rights_needed(reguest): if request.user.groups.filter(Q(name='Admin')).exists(): pass else: return HttpResponseRedirect('/account/log-in/') @method_decorator(right_needed, name='dispatch') class AdminView(CreateView): model = Admin form_class = AdminForm def get_template_names(self): return 'clinic/visitform_list.html' Could help me know how I can achieve this? Or an easier way around it? I also tried this (code inside AdminView class): def dispatch(self, request): if request.user.groups.filter(Q(name='Admin')).exists(): return super().dispatch(*args, **kwargs) else: return HttpResponseRedirect('/account/log-in/') -
Dynamic Django-REST API Endpoint in jQuery
I have a view which calls results_chart.html which contains a jquery block which specifies an REST-API endpoint. This endpoint is currently hardcoded like: var endpoint = '/api/solgeo/projects/2.json'; However of course I want the correct project id, which I can access in the {% block content %} section using Django templating. I.e. the project Id is specified by {{project.id}}. How can I access this project.id in my jQuery section? The html template in question is given by: {% extends 'base.html' %} <script> {% block jquery %} var endpoint = '/api/solgeo/projects/2.json'; var defaultData = [] var labels = [] $.ajax({ method: "GET", url: endpoint, success: function(data){ var length = data.hourlys.length for (i=0; i<length; i++){ defaultData[i] = data.hourlys[i].clock_time labels[i] = i.toString() } console.log("The default data is: " + defaultData.toString()) setChart() }, error: function(error_data){ console.log("error") console.log(error_data) } }) function setChart(){ var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: '# ??????', data: defaultData, }] } }) } {% endblock %} </script> {% block content %} <h3>Project id: {{ project.id }}</h3> <div class='row'> <div class='col-sm-12'> <canvas id="myChart" width="400" height="400"></canvas> </div> </div> {% endblock content %} -
DRF - Django Url Filter - RelatedFieldError
I am working on DRF generic listview with DUF as filter backend. Could you please assist me to get around this error? I am sure i am doing something wrong here with related to related fields. When i try to filter on url I get the following error. I would like to filter on all columns of child model. http://127.0.0.1:8000/api/childlist/?customer_id=2 AttributeError at /api/childlist/ 'OneToOneField' object has no attribute 'rel' Below is my work so far: models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Parent(models.Model): customer_id = models.BigIntegerField(primary_key=True) customer_name = models.CharField(blank=True, null=True, max_length=50) age = models.IntegerField(blank=True, null=True) class Child(models.Model): customer_id = models.OneToOneField(Parent, on_delete=models.DO_NOTHING, related_name='customer_id_fk_parent') used_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='rel_user') comments = models.TextField(blank=True,null=True) views.py from rest_framework import generics from onetoone.models import Child from .serializers import Child_Serializer from url_filter.integrations.drf import DjangoFilterBackend #Required columns on Child -- All columns FILTER_REQ_COLUMNS = [field.name for field in Child._meta.get_fields()] class ChildList(generics.ListAPIView): queryset = Child.objects.all() serializer_class = Child_Serializer filter_backends = [DjangoFilterBackend] filter_fields = FILTER_REQ_COLUMNS serializers.py from rest_framework import serializers from onetoone.models import Child class Child_Serializer(serializers.ModelSerializer): class Meta: model = Child exclude = [] urls.py path('childlist/', ChildList.as_view(), name='api_child_list'), Current list data as below http://127.0.0.1:8000/api/childlist/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: … -
How to pass values from a dropdown list to the view in django
I have searched quite extensively for a clear answer to my problem but have not been able to find anything. I have am currently displaying the first 5 items from a database and want to add a feature that allows the user to toggle between ascending and descending order using the current rent column. But i am having trouble passing the request from the dropdown list and returning a new sql query dependant on the users input. HTML FILE Views.py -
Share Heroku postgresql with desktop app
I am using Heroku Postgresql in django(Python framework) app but now a days i am working on a desktop version of my application using same language that is Python. So, How can i connect my desktop(Python app) to heroku postgesql database. Or any other best option is always welcome. -
Django Ajax get request - load model instance into a form
I have a table in a HTML template that displays all instances of a django model. on each row of the template I have an edit button that looks up the primary key of each instance, and by clicking that button I want all the fields in the model instance to be populated in a modal by using ajax. After that I want to be able to edit the data and use ajax to send the edited data back to the database. I have been searching all over the web and found this post that is exactly what I need, but I still can't get it to work. Any help would be greatly appreciated. jQuery code var modalDiv = $("#modal-div"); $(".open-modal").on("click", function() { console.log("button clicked"); var url = $(this).attr('data-url').replace('/', ''); console.log("url:",url); // this returns my customer number but is not used in the code below $.ajax({ url: $(this).attr("data-url"), type: 'get', success: function(data) { console.log("success"); modalDiv.html(data); $("#myEdit").modal(); //#myEdit is the ID of the modal }, error : function() { console.log("Error: this did not work"); // provide a bit more info about the error to the console } }); }); a tag in form <a class="btn open-modal" data-url="{% url 'dashboard:customer_update' kunde.kundenr %}">Edit</a> … -
How can i fix this when CSS not work in Django Framework?
This is how my Django admin panel appears -
raise RuntimeError('You need to use the eventlet server. '
In my project, I created a app: the website_chat/views.py code: async_mode = 'eventlet' import os from django.http import HttpResponse import socketio basedir = os.path.dirname(os.path.realpath(__file__)) sio = socketio.Server(async_mode=async_mode) thread = None the website_chat/management/commands/runserver.py: from django.core.management.commands.runserver import Command as RunCommand from xxx/website_chat.views import sio class Command(RunCommand): help = 'Run the Socket.IO server' def handle(self, *args, **options): if sio.async_mode == 'threading': super(Command, self).handle(*args, **options) elif sio.async_mode == 'eventlet': # deploy with eventlet import eventlet import eventlet.wsgi from Qiyun02.wsgi import application eventlet.wsgi.server(eventlet.listen(('', 8002)), application) elif sio.async_mode == 'gevent': # deploy with gevent from gevent import pywsgi from Qiyun02.wsgi import application try: from geventwebsocket.handler import WebSocketHandler websocket = True except ImportError: websocket = False if websocket: pywsgi.WSGIServer( ('', 8000), application, handler_class=WebSocketHandler).serve_forever() else: pywsgi.WSGIServer(('', 8000), application).serve_forever() elif sio.async_mode == 'gevent_uwsgi': print('Start the application through the uwsgi server. Example:') print('uwsgi --http :5000 --gevent 1000 --http-websockets ' '--master --wsgi-file django_example/wsgi.py --callable ' 'application') else: print('Unknown async_mode: ' + sio.async_mode) In my wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Qiyun02.settings") from socketio import Middleware from website_chat.views import sio django_app = get_wsgi_application() application = Middleware(sio, django_app) But when I runserver I get the bellow error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, … -
D3, Django, and hierarchical many-to-many relationships
I started a project in Django with most of the front-end rendering being done in D3.js. This stems from an old database project I had that was built in MySQL, but I'm just now getting around to building an interface for it. My biggest issue at the moment is handling a self-join many-to-many relationship. In MySQL, I used an adjacency table off the main table. For example: |ParentID | ChildID | "Extra data" | |[ItemID1]|[ItemID2] | "Some comment" | |[ItemID1]|[ItemID3] | "Some comment" | |[ItemID2]|[ItemID4] | "Something " | |[ItemID3]|[ItemID4] | "Somethingelse"| Without going into details about the data itself, there is a lot of hierarchy that needs to be preserved. Parent items have multiple children; children can have multiple parents. I need recursion both ways from top-to-bottom. A nested approach doesn't seem appropriate, as the data in the Items fields are the focus of what I'm building; the relationships between Items are a more of a bonus feature. Ideally, it would be nice if that could be passed to D3 in a JSON format that could make nodes or trees to visualize the data (serialize didn't seem to work as intended, and I'm not sure if it's the appropriate … -
Permissions django in template
How to make certain groups of users set in the admin panel can access only certain content on the site. Maybe you have examples of works in which it is implemented. -
django-import-export exporting files without id and user but importing with user and header
I want to export csv files without id and user but when I import, I want it to have an autoincrementing id based on the number of contacts and the user be the request.user. Here is my model: class Contact(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) contact_number = PhoneNumberField(help_text="Please put country code at start of number. eg: +639171231234") address = models.CharField(max_length=255) def __str__(self): return self.first_name + " " + self.last_name and here is my resources.py from import_export import resources from .models import Contact class ContactResource(resources.ModelResource): class Meta: model = Contact exclude = ('id', 'user') Here is my views for import and export def export_csv(request): queryset = Contact.objects.filter(user=request.user) contact_resource = ContactResource() dataset = contact_resource.export(queryset) response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="contacts.csv"' return response def import_csv(request): if request.method == 'POST': contact = Contact.objects.filter(user=request.user) contacts_resource = ContactResource() dataset = Dataset() new_contacts = request.FILES['import-csv'] imported_data = dataset.load(new_contacts.read().decode('utf-8'),format='csv') for header in dataset.rows: dataset.id = request.user.id dataset.user = request.user dataset.id =+ 1 contacts_resource.import_data(dataset, dry_run=False) return render(request, 'addressbook/import.html', {}) I think I know the logic, I just don't know what attribute to use.