Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I reduce recursive MPTT tree queries when serializing with DRF
Working on an e-commerce project. Project has related models. Category model has MPTT inheritance. It using Django Rest Framework for communicate between API's. An foreign service recently wants me to put full Category path into XML response on my side. But this request caused very high db queries. I need to reduce queries but I can't figured out how to do this within DRF serialization. I tried a few way. My final approach is below with model view and serializations. On each product object serialization produces very high amount of Category model query. class Category(MPTTModel): parent = TreeForeignKey('self', blank=True, null=True, related_name='children') root = TreeForeignKey('self', blank=True, null=True, related_name='leaf') name = models.CharField(max_length=100) class ProductMeta(models.Model): ... category = models.ForeignKey('Category', null=True, blank=True, db_index=True, related_name='category') ... class Product(models.Model): ... meta = models.ForeignKey(ProductMeta, related_name='product') ... And some DRF viewsets are renders model data to XML class ProductMetaBaseViewSet(viewsets.ModelViewSet): def get_serializer_class(self): return ProductMetaSerializer def get_queryset(self): queryset = ProductMeta.objects.all().prefetch_related('products', 'category__root' return self.paginate_queryset(queryset) def list(self, request): serializer = ProductMetaSerializer(self.get_queryset(), many=True) return Response(serializer.data) class ProductMetaXMLViewSet(ProductMetaBaseViewSet, viewsets.ModelViewSet): parser_classes = (XMLParser,) renderer_classes = (XMLRenderer,) And here is the serializers to get data: class RootCategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name') class CategorySerializer(serializers.ModelSerializer): root = RootCategorySerializer() full_category_path = serializers.SerializerMethodField() class Meta: … -
Make django view a “singleton” temporary in django rest
I didn’t know how to title this question, honestly. Suppose a view like this below. My users can have maximum 10 dollars in their pocket. I’ve added a button that hits this view, and adds 1 dollar at time until 10 is reached. This is just an example. def my_view(request): money_to_add = 10 - request.user.money for i in range(0, money_to_add): user.money += 1 return HttpResponse(“Ok!”) Problem is that if the user clicks very fast the button two times, then ‘10 - request.user.money’ is added twice to the account. How can i solve this problem, just modifying the view? I’d prefer avoid to use external packages or modify the model’s behavior. Thank you. EDIT: Using class based views is ok! I just used a fbv for example to make it clear. -
Django multiple user with user model
I have problem about multiple django user. There are 3 types user. 1. CompanyContact(Enduser) - Can give order 2. Staff - can change status of order or update .. 3. Courier - After order status changed to "Ready for delivery" Courier able to see that orders . Also Courier can change status to "On delivery". Fields are looks similar just they have foreignkey but problem start company contact is end user others are using staff page. Permission and User model will be enough for it? I checked many resources which they are using django USER model and extend it. I Tried OneToOne relations can't figure out how to make it class CompanyContact(models.Model): fk_company = models.ForeignKey('Company', on_delete=models.CASCADE, verbose_name=_('Company Contact')) title = models.CharField(max_length=256 , verbose_name=_("Title")) first_name = models.CharField(max_length=256, verbose_name=_('First Name')) last_name = models.CharField(max_length=256, verbose_name=_('Last Name')) email = models.EmailField(verbose_name=_('Email')) telephone = models.CharField(max_length=11,verbose_name=_('Telephone')) notes = models.TextField(verbose_name=_('Notes')) no_marketing_email = models.BooleanField(default=True,verbose_name=_('Marketing Email')) Courier & Staff Title Firstname Surname Email Phone isExternalCourier (bit) fk_CourierCompanyID -
Set a default custom AWS SNS sender ID using boto3
What I have found out is that to set Custom AWS SNS Sender ID we can set it directly while sending an SMS. response = AWS_SNS_CLIENT.publish( PhoneNumber=mobile_number, Message='OTP to login into your account', Subject='One Time Password', MessageAttributes={ 'AWS.SNS.SMS.SenderID': { 'DataType': 'String', 'StringValue': sender_name } } I want to know whether there is any way to set Sender ID by default and not to mention it every time when we are sending SMS. -
How to pass a json to a serializer to store in model
my record/model.py is, class HistoricalRecords(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE, null=True, blank=True) role = models.CharField(max_length=255, null=True, blank=True) model = models.CharField(max_length=255, null=True, blank=True) torque = models.IntegerField(null=True, blank=True) car = models.TextField(null=True, blank=True) date_time = models.DateTimeField(default=timezone.now) my record/serializer.py is class SaveAuditRecordSerializer(serializers.ModelSerializer): class Meta: model = HistoricalRecords fields = ('user', 'role', 'model', 'torque', 'car', 'date_time') and my record/views.py is, def AuditRecord(request): serializer = SaveAuditRecordSerializer(data=request, partial=True) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_201_CREATED) I am trying to call this AuditRecord(req) from another view of another app, like rec = {} audit_record['user'] = request.user audit_record['role'] = "Role" audit_record['model'] = "M" audit_record['torque'] = 22222 audit_record['action'] = "car created" audit_record['date_time'] = datetime.now() AuditRecord(audit_record) I dont get any error but it is not getting saved to db is there any mistake in my approch? -
How to restore files from secondary model when using Reversion app (DJANGO)
I have 2 models: Model1(models.Model): and Model2(models.Model): fk = models.ForeignKey("Model1", on_delete=models.CASCADE) image = models. ImageField(…..) I use Reversion app to restore all deleted data and both models are registered in admin with Version admin. It works but when I restore any entry of model1 it would not restore actual files from Imagefield of the Model2. Thats reasonable because they are deleted by CASCADE. If I set on_delete = DO_NOTHING, it would rise integrity error as Postgree supports cross table integrity protection. Thats reasonable as well. If I use SET_NULL , then Reversion would not be able correctly restore images as it would loose foreignkey ID obviously. Question is how to restore associated images of the Model2 within data of the Model1 by Reversion or alternatively keep foreignkey ID of the Model2’s images intact if I use something outside CASCADE in order to not delete the images from the file system? Thank you! -
Django pagination query duplicated, double the time
In my current project I want to do some filtering and ordering on a queryset and show it to the user in a paginated form. This works fine, however I am not comfortable with the performance. When I use and order_by statement either explicitly or implicitly with the model Meta ordering, I can see in the Debug toolbar that this query is essentially executed twice. Once for the paginator count (without the ORDER BY) and once to fetch the objects slice (with ORDER BY). From my observation this leads to doubling the time it takes. Is there any way this can be optimized? Below is a minimal working example, in my actual app I use class based views. class Medium(models.Model): title = models.CharField(verbose_name=_('title'), max_length=256, null=False, blank=False, db_index=True, ) offered_by = models.ForeignKey(Institution, verbose_name=_('Offered by'), on_delete=models.CASCADE, ) quantity = models.IntegerField(verbose_name=_('Quantity'), validators=[ MinValueValidator(0) ], null=False, blank=False, ) deleted = models.BooleanField(verbose_name=_('Deleted'), default=False, ) def index3(request): media = Medium.objects.filter(deleted=False, quantity__gte=0) media = media.exclude(offered_by_id=request.user.institution_id) media = media.filter(title__icontains="funktion") media = media.order_by('title') paginator = Paginator(media, 25) media = paginator.page(1) return render(request, 'media/empty2.html', {'media': media}) Debug toolbar sql timings -
DetailView with data from two other Models
I would like to get some advice from the community. I have recenlty started learning Django and have a question regarding the structure of the application. I have a URL http://127.0.0.1:8000/asset/2/, a DetailView for my Asset model which also has two card blocks that houses data for two other models Tenant and Service. Check the screenshot below. I am generating the above view from the asset/views.py file. Code as below. class AssetMultipleDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = Asset context_object_name = 'asset' template_name = 'asset/asset_multiple_detail.html' def test_func(self): asset_multiple = self.get_object() if self.request.user == asset_multiple.owner: return True return False def get_context_data(self, **kwargs): context = super(AssetMultipleDetailView, self).get_context_data(**kwargs) context['tenants'] = Tenant.objects.filter(asset=context['asset']).order_by('created') context['services'] = Service.objects.filter(asset=context['asset']).order_by('created') return context When you click on the Add New Tenant button, I use the below URL in tenant/urls.py path('new/asset/<int:pk>/', TenantAssetCreateView.as_view(), name='tenant_asset_create'), This URL generates a CreateView for Tenant. I use the primary key of the asset in the URL to load up only the right asset to the Asset selection field. Please see the image below. Everything works well. I would like to know whether is this the best way to achieve this? Will this be easily maintainable as there are more views similar to this upcoming in the application. Any … -
Passing a django variable to javascript
I want to pass a django variable which is a dictionary like this {u'testvar1': u'1', u'testvar2': u'38', u'testvar3': u'160'} to javascript.How can I do this?I cant seem to find a solution for the same.I am new to django so sorry for this noobie question. -
Passing and printing variable created from DB into template
In veiws.py I have created hostname variable based on db value. passing it successfully into GET request url, hence i assume variable is fine. Now i simply want to pass this variable into template alongside with API response and view on top of this webpage, above API response. With this setup, only API response is rendered. Like hostname variable is not passed at all. views.py def about_abc(request, host_id): hostname = Host.objects.get(pk=(host_id)) response = requests.get( 'https://{}:1768/abc/api/v1/about'.format(hostname), verify='/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxxxxx'}, ).json() context = {'response': response} host_context = {'hostname': hostname} return render(request, 'itpassed/json.html', context, host_context) json.html <h1>{{ hostname }}</h1> {% if response %} {% for id, value in response.items %} <p>{{ id }}: {{ value }}</p> {% endfor %} {% else %} <p>No IDs are available.</p> {% endif %} Having in mind that hostname variable is fine because its filling url in request just fine, what am i doing wrong? -
Is it possible to resolve the get object?
Trying out Django first time and my product view is now fetching data through templates.Occasionally, pycharm warns about invalid indent, but I resolved it with unnecessary space. Here is the 'base.html' file: <!doctype html> <html> <head> <title>Programmierung ist schön.</title> </head> <body> <!-- <h1>This is navbar</h1> --> {% include 'navbar.html' %} {% block content %} replace me {% endblock %} {% block another_content %} replace me {% endblock another_content %} </body> </html> Here is the product\detail.html file: {% extends 'base.html' %} {% block content %} <h1>{{ item }}</h1> <p>{ % if description } {{ description }} { % else % } Description Coming Soon { % endif % }</p> {% endblock %} Error from Safari Browser: AttributeError at /product 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/product Django Version: 2.0.7 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' Exception Location: /Users/kuldeep/Dev/trydjango/lib/python3.7/site-packages/django/middleware/clickjacking.py in process_response, line 26 Python Executable: /Users/kuldeep/Dev/trydjango/bin/python Python Version: 3.7.0 Python Path: ['/Users/kuldeep/Dev/trydjango/src', '/Users/kuldeep/Dev/trydjango/lib/python37.zip', '/Users/kuldeep/Dev/trydjango/lib/python3.7', '/Users/kuldeep/Dev/trydjango/lib/python3.7/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Users/kuldeep/Dev/trydjango/lib/python3.7/site-packages'] Server time: Mon, 29 Apr 2019 09:53:16 +0000 -
django.urls.exceptions.NoReverseMatch: Reverse for ' ' not found. ' ' is not a valid view function or pattern name
I receive the following error when I try to save input in the database. Where the 13 the value is that I try to post into the database. raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for '13' not found. '13' is not a valid view function or pattern name. I think that it has something to do with my URLs, but I can't seem to figure out what the issue is. urls.py from django.conf.urls import url, include from . import views app_name= 'service-development' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^choice/(?P<element_id>[0-9]+)/(?P<session_id>[0-9]+)$', views.choice, name='choice'), url(r'^message/(?P<element_id>[0-9]+)/(?P<session_id>[0-9]+)$', views.message_presentation, name='message-presentation'), url(r'^start/(?P<voice_service_id>[0-9]+)$', views.voice_service_start, name='voice-service'), url(r'^start/(?P<voice_service_id>[0-9]+)/(?P<session_id>[0-9]+)$', views.voice_service_start, name='voice-service'), url(r'^user/register/(?P<session_id>[0-9]+)$', views.KasaDakaUserRegistration.as_view(), name = 'user-registration'), url(r'^language_select/(?P<session_id>[0-9]+)$', views.LanguageSelection.as_view(), name = 'language-selection'), url(r'^record/(?P<element_id>[0-9]+)/(?P<session_id>[0-9]+)$', views.record, name='record'), url(r'^InputData/(?P<element_id>[0-9]+)/(?P<session_id>[0-9]+)$', views.InputData, name='InputData') ] view def InputData(request, element_id, session_id): input_element = get_object_or_404(InputData_model, pk=element_id) voice_service = input_element.service session = lookup_or_create_session(voice_service, session_id) if request.method == "POST": session = get_object_or_404(CallSession, pk=session_id) value = 'DTMF_input' result = UserInput() #result.input_value = request.POST.get("input_value") result.input_value = request.POST['input_value'] result.session = session result.category = input_element.input_category result.save() return redirect(request.POST['input_value']) template <form id="input_form"> <property name="interdigittimeout" value="2s"/> <property name="timeout" value="4s"/> <property name="termchar" value="#" /> <field name="input_value" type="digits?minlength=1;maxlength=5"> <prompt> <audio src="{{ ask_input_label }}"/> </prompt> <filled> <assign name="input_value" expr="input_value"/> <!--namelist="DTFM_input"--> <submit next="{{ redirect_url }}" enctype="multipart/form-data" namelist="input_value" method="post"/> <!--<submit next="{{redirect_url}}" namelist="input_value" method="post"/>--> </filled> </field> … -
Failed to starting the worker process Celery task with Django in debug = False (production)
This is a Celery task for sending email, the funny thing that everything works correctly in DEBUG = True mode, but it does not work in productionDEBUG = False. Running celery worker -A invoice2 --loglevel = debug during the send action and in debug mode activated shows the following: ERROR/ForkPoolWorker-5] Task enviar_documentos[xxx] raised unexpected: TypeError("enviar_documentos_async() got an unexpected keyword argument 'cliente'",) First the file that starts the send with the delay: from django.conf import settings from notifications.tasks import send_async_documents def send_documents (company, client, documents, type, template = "invoice", context = None): send_documents = send_documents_async.delay send_documents (type = type, company = company.pk, client = client.pk, template = template, context = context) Second, the task: from celery_app import app @app.task (name = "send_documents") def enviar_documentos_async (company, client, documents, type = "FacturaVenta", template = "invoice", context = None): if not context: context = {} klass = KLASS.get (type) queryset = klass.objects.filter (pk__in = documents) em = Empresa.objects.get (pk = company) cl = Cliente.objects.get (pk = client) . . return send_email( mail_from = "\"{0.name}\"><{0.email}>".format(em), mail_to = cl.email, type = template, context = context, attachments = attachments) Third, the sending of the email: from django.core.mail import EmailMessage from django.template import Context, Template def send_email(mail_from, mail_to, … -
django.core.exceptions.ImproperlyConfigured. When I tried running a python program on my local machine, I encounted this error
When I tried running a python program on my local machine, I encountered this error: Traceback (most recent call last): File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 50, in get_internal_wsgi_application ) from err django.core.exceptions.ImproperlyConfigured: WSGI application 'mysite.wsgi.application' could not be loaded; Error importing module. There are also similar posts online, and I tried the suggested solution from each post, but none of them could solve my error. Here is the content of my setting.py My python version: Python 3.7.3 My Django verison: 2.2 """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.0.7. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os import django_heroku import dj_database_url config = dj_database_url.config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # … -
Unable to delete items from Django sqlite3 database, with error "foreign key constraint failed"
There are some items that are not deletable or editable from my Django sqlite3 database. When trying to delete these items, I get "integrity error: foreign key constraint failed." The frustrating thing is that this isn't the case with the majority of items in my database. I believe it is only affecting a few rows, which I must have created before making some tweaks to the models. I don't recall what exact changes I made to the models file, but I don't think it was anything drastic. I don't have information about the migrations I made, because I deleted these files thinking that it might resolve the problem. I have included an example of how the classes in models.py are currently set up. Nothing complicated -- standard models with a simple foreign key, which isn't even a required field. I have tried editing my migrations files, completely removing my migration history, editing the models via models.py. #models.py class ExampleOne(models.Models): title = model.CharField(max_length=500, null=True, blank=True) class ExampleTwo(models.Models): title = model.CharField(max_length=500, null=True, blank=True) example_one = models.ForeignKey(ExampleOne, null=True, blank=True) I'd rather not delete my database file. I'd to be able to delete these instances of exampleone and exampletwo, but when I try to … -
Is there any way to rename the django.auth tables?
I am writing an app with Django 2.1.5 using an Oracle database. The folks that maintain the database want all tables to follow a specific format, where the table is prefixed by the project name and suffixed with "_TAB". I've managed to find out, that I can set the internal table name for a Django model using the db_table attribute of the models Meta class. However, I can't seem to find a way to also rename Djangos user, group, and permission tables. Is there any way to rename the django.auth tables names? -
How to connect a model with foreign key in a function which uploads a csv file in django?
I have a django web app where I want users to upload their data in the form of csv. I have created a function and a page where the user uploads csv, and I have appended the user to the model, but I want that user to be the foreign key for each of the files. From what I see, the data is being entered in the database just fine but I do not think it is properly connected with a foreign key because on analyzing the database it says there are no foreign keys connected, and just the value is being entered with no relation what so ever. Here is my function: def upload_batch(request): template_name = 'classroom/teachers/upload.html' prompt = {'order':'Order of csv should be first_name, last_name, email, ip_address, message'} if request.method == "GET": return render(request,template_name,prompt) csv_file = request.FILES['file'] data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) uploaded_by = request.user for column in csv.reader(io_string,delimiter=',',quotechar='|'): _, created = ItemBatch.objects.update_or_create( name = column[0], pid = column[1], quantity = column[2], length = column[3], width = column[4], height = column[5], volume = column[6], weight = column[7], uploaded_by = uploaded_by ) context = {} return render(request,template_name,context) Here is my model: # item upload class ItemBatch(models.Model): # … -
Assign Foreign Key Value after creating ( Logged In User )
I have a createview using CBV class StudentCreate(LoginRequiredMixin, CreateView): login_url = '/signin/' model = Student fields = ['first_name', 'last_name' ] success_url = '/dashboard/' Respective models.py class Class_teacher(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) standard = models.IntegerField() division = models.CharField(max_length=1) subject = models.CharField(max_length=200) email = models.CharField(max_length=30) class Student(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) classteacher = models.ForeignKey('Class_teacher', on_delete=models.SET_NULL,blank=True, null=True ) The webapp has a login feature . When the user ( classteacher ) login they can add students. What I want is classteacher field in Student(model Form ) should be automatically set as user which is the classteacher. ( Classteacher ) and should be saved in the db after creating the student. Classteacher model is updated with respective required fields . -
How to access column from another table in list_display?
I have this database relation: Now suppose I want list_display of the orders model to show the columns order_id, user_id, status, created_at, quantity I know I could do something like this: class OrdersAdmin(admin.ModelAdmin): list_display = ('id', 'user_id', 'status', 'created_at', 'get_quantity') class Meta: model = Orders def get_quantity(self, obj): result = XXX return result.get('quantity') get_quantity.short_description = 'Quantity' admin.site.register(Order, OrderAdmin) How can I access the information I need at XXX? -
objects.filter by User filters data only for one user
I want to filter data from th model, using user PK (the best way it is ussing session, but i don't now how works with). This my model.py: class Fca(models.Model): num_of_agree = models.ForeignKey(Agreement, models.DO_NOTHING, blank=True, null=True) uroch = models.TextField(blank=True, null=True) num_allot = models.ForeignKey(Allotment, models.DO_NOTHING, blank=True, null=True) num_fca = models.CharField(max_length=50, blank=True, null=True) ar_fca = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) expl_ar = models.FloatField(blank=True, null=True) cel_nazn = models.ForeignKey(ForestPurpose, on_delete=models.DO_NOTHING, verbose_name='task',blank=True, null=True) cat_zas = models.ForeignKey(ForestProtection, on_delete=models.DO_NOTHING, verbose_name='cate',blank=True, null=True ) geom = models.MultiPolygonField(geography=True, null=True, blank=True, verbose_name='ge') video_cat = models.TextField(blank=True, null=True) user_check = models.ForeignKey(User,on_delete=models.DO_NOTHING, verbose_name='user_id',blank=True, null=True ) class Meta: managed = True verbose_name = 'lek' verbose_name_plural = 'leks' so user_check is a filter. Look at serializer.py: class FcaSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = Fca geo_field = 'geom' fields = ('id','num_of_agree','num_allot','uroch','num_fca','ar_fca',\ 'expl_ar','cel_nazn','cat_zas','geom','video_cat','user_check') def create(self, validated_data): return Fca.objects.create(**validated_data) and the view queryset def: class FcaSet(viewsets.ModelViewSet): serializer_class = FcaSerializer permission_classes = [IsAuthenticated] def get_queryset(self): user = self.request.user.pk return Fca.objects.filter(user_check = user) So when I login user with pk 1, app shows relevant data (where user has pk 1). /api/fcaapi/ shows only relevant data too. But when I use other users, with pk 3 for example, app shows same data (where pk of user = 1). What is wrong? How to show … -
Slicing starting from a particular item given a specific order
I am trying to implement a cursor-based pagination on Django. I learned a basic knowledge through https://www.sitepoint.com/paginating-real-time-data-cursor-based-pagination/ I know I need a cursor which points where I am. Before and after. (If I know 'count', I will be able to decide before or after by calculating before + count = after) But I have no idea how to get them by using Django. What I want to do should be like this: posts = Post.objects.order_by('-created_date')[after:after+count] But I do not know how to get the after index of a particular item, which is a cursor in this case. I can only think of it in a Python level. post = Post.objects.get(slug=slug) queryset = Post.objects.order_by('-created_date') after = list(queryset).index(post) result = queryset[after:after+count] In this way, I have to query all the objects from the whole model. I do not think it is ideal, but I do know know either how to execute a query to get the index from a particular item or slice from a particular item. I only know of a post's slug. My client does not have a primary key. The dataset is never ordered by slugs, but slug is a unique key. -
vue.js tree list ajax
I'm going to convert the following data into AJAX communications. url in reference https://vuejsexamples.com/a-vue-component-for-tree-structure/ new Vue({ el: '#app', components: { 'VueTreeList': VueTreeList.VueTreeList }, data () { return { isMobile: isMobile(), record: null, newTree: {}, data: new VueTreeList.Tree([ { name: 'Node 1', id: 1, pid: 0, dragDisabled: true, children: [ { name: 'Node 1-2', id: 2, isLeaf: true, pid: 1 } ] }, { name: 'Node 2', id: 3, pid: 0 }, { name: 'Node 3', id: 4, pid: 0 } ]) } }, I tried. change the hardcoded part.... new Vue({ el: '#app', components: { 'VueTreeList': VueTreeList.VueTreeList }, data () { return { isMobile: isMobile(), record: null, newTree: {}, data: new VueTreeList.Tree([]), mounted: function () { var self = this; $.ajax({ url: '/ajax_call/TemplateLVFolder', method: 'GET', success: function (data) { self.VueTreeLis.Tree= data; }, error: function (error) { console.log(error); } }); } } }, urls.py The composition is as follows. path('ajax_call/TemplateLVFolder', views.Templete_folder, name='TemplateLVFolder') I don't think I'm getting the data. How do I get the data? -
Do not save model on duplicate file - Django 2
I am trying to check for an existing file and overwriting it, so far I am able to do it using a custom storage, which looks something like this from django.core.files.storage import FileSystemStorage class DuplicateFileStorage(FileSystemStorage): def get_available_name(self, name, max_length=None): return name def _save(self, name, content): if self.exists(name): self.delete(name) return super(DuplicateFileStorage, self)._save(name, content) The above class checks for an existing file and deletes it. And the model it looks after is: class DataStorageModel(models.Model): user = models.ForeignKey(User, related_name='data_storage', on_delete=models.CASCADE) file_name = models.CharField(blank=True, max_length=200, help_text="File Name") file = models.FileField(blank=True, null=True, upload_to=user_directory_path, storage=DuplicateFileStorage()) relative_path = models.CharField(blank=True, max_length=200, help_text="Relative Path if folder else null") def delete(self, using=None, keep_parents=False): self.file.delete() return super(DataStorageModel, self).delete() The problem is that though it removes and writes the same file it also creates a new model entry with the same existing path, that is if I upload the same file twice, I get one file in the OS path but two model entries. Something like this (there is an image here): So I tried using the clean() method with self.file.storage.exists(self.file.name) (according to this) but I get the existance as False, even though there is a file there. def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.full_clean() return super(DataStorageModel, self).save() def clean(self): print(self.file.storage.exists(self.file.name)) # … -
LookupError: No installed app with label 'admin'. when I tried running a program using Django
I was trying to run a python program on my computer, the command I use is py -3 manage.py runserver, but I ran into an error and I couldn't find any helpful posts online that can solve this problem. Python version is Python 3.7.3 Django version is 2.2 Here is the error message: Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Thomas\Desktop\Intern\Diversity_Policy_Site\blog\models.py", line 4, in <module> from .search import PolicyIndex File "C:\Users\Thomas\Desktop\Intern\Diversity_Policy_Site\blog\search.py", line 14, in <module> connections.create_connection(hosts=["https://dd90577b842c4f9396ca1846612e98df.us-east-1.aws.found.io:9243"], … -
Passing db.sqlite3 value into the middle of url in GET request
I am doing webapp which uses external API. What i am trying to do is generic view. In order to do this i will have to enter DB value into the middle of url specified in GET request. So my DB models: models.py from django.db import models class Host(models.Model): abchostname = models.CharField(max_length=50) abcshortname = models.CharField(max_length=50, default="plx") def __str__(self): return self.cfthostname So i have webpage with all listed hosts from DB: def index(request): abc_hosts = Host.objects.all() context = {'abc_hosts': abc_hosts} return render(request, 'itpassed/index.html', context) {% if abc_hosts %} <ul> {% for host in abc_hosts %} <li><a href="/itpassed/{{ host.id }}/">{{ host.abchostname }}</a></li> {% endfor %} </ul> {% else %} <p>No ABCs are available.</p> {% endif %} when i click one of listed hostnames, host id from db is passed to url and now for example when i click 3rd listed host, i get http:/hostname.net/itpassed/3/ into url. next, in this page i have listed link to about_abc view views.py def about_abc(request, host_id): response = requests.get( 'http://hostname.net:1768/abc/api/v1/about', verify='/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxx'}, ).json() context = {'response': response} return render(request, 'itpassed/json.html', context) What i would like to do is to put abchostname value from DB into url in GET request http://hostname.net:1768/abc/api/v1/about instead of hostname.net. …