Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django copy instances bulk create
What is the best way to copy django objects for bulk creating, when multiple fields may vary between instances? for example i have: objects_to_create = [] for i in range(5): new_obj = obj new_obj.pk = None new_obj.foo = i objects_to_create.append(new_obj) M.objects.bulk_create(objects_to_create) However, for all of these newly created objects, foo will have value 4, because bulk create is saving 5 instances of new_obj as it is at the end of the loop. Is there a way to create copies that can then be modified before saving? Thanks. -
Spyne. How can i make service for one tag xml
Worked on python 2.7, django 1.6, spyne 2.11 I have this xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE inquiry_A2 SYSTEM "inquiry_A2.dtd"> <!-- Optional --> <inquiry_A2> <!-- Optional --> <Consignee> <AgencyCode>123123</AgencyCode> <PartyID>123123</PartyID> </Consignee> <SubstitutionIndicator>123123</SubstitutionIndicator> <Campaign>123123</Campaign> <DocumentID>1</DocumentID> </inquiry_A2> inquiry_A2 is a root element I want to make spyne proceed this request, but i can't figure out how to make this? The problem is that spyne rpc need both method name and param, for example: @rpc(RequestInquiry) def inquiry_A2(ctx, inquiry_A2): return True But with this example spyne generated xml is: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE inquiry_A2 SYSTEM "inquiry_A2.dtd"> <!-- Optional --> <inquiry_A2> <inquiry_A2> <!-- Optional --> <Consignee> <AgencyCode>123123</AgencyCode> <PartyID>123123</PartyID> </Consignee> <SubstitutionIndicator>123123</SubstitutionIndicator> <Campaign>123123</Campaign> <DocumentID>1</DocumentID> </inquiry_A2> </inquiry_A2> Is that possibile to do with spyne? I can't change incoming xml -
install Django 2.0.2 Could not find a version
Im trying to use pip install Django==2.0.2 but throw , No matching distribution found for Django==2.0.2 , and it´s weird cause im using the same command from Django, what can i do ? -
django error while installing
Getting error while installing Django C:\Users\Lenovo>pip install django Collecting django Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/django/ Could not find a version that satisfies the requirement django (from versions: ) No matching distribution found for django -
'image' attribute has no file associated with it - django
I have a blog project, and receive the above error when running the django dev server. I have uploaded an image via the admin panel, which then saves as expected in the posts/media folder. Please can anyone help? My project (shortened version) looks as follows: - blogproject - posts - media - static - templates - posts - base.html - getAllPosts.html - blog - urls.py - settings.py - models.py SETTINGS.PY BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [STATIC_DIR, ] STATIC_URL = '/static/' MEDIA_DIR = os.path.join(BASE_DIR, 'posts/media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' URLS.PY [...] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Post(models.Model): title = models.CharField(max_length=200) summary = models.CharField(max_length=500, default=True) body = models.TextField() pub_date = models.DateTimeField(default=timezone.now) category = models.ManyToManyField('Category') author = models.ForeignKey(User, default=True) titleSlug = models.SlugField(blank=True) authorSlug = models.SlugField(blank=True) image = models.ImageField(upload_to="images/%Y/%m/%d", null=True) def save(self, *args, **kwargs): self.titleSlug = slugify(self.title) self.authorSlug = slugify(self.author) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title getAllPosts.html <!DOCTYPE html> {% extends "posts/base.html" %} {% load static %} {% load template_tags %} {% block content %} {% if latest_posts %} {% for post in latest_posts %} <a href="{% url 'getPost' slug=post.titleSlug %}"> <img src="{{ MEDIA.URL }} {{post.image.url}}" alt="image- {{post.title}}"/> … -
I want to built a multiple items search at a time like user can search for (rice, potato, eggs, etc) multiple items at once
This is my current search view.py. I am trying to split the whole search string by (, ) and then take each word to return each searched product. But that's not working.Can anyone give any idea on how should I approach this? from django.shortcuts import render from django.views.generic import ListView from products.models import Product class SearchProductView(ListView): template_name = "search/view.html" def get_context_data(self, *args, **kwargs): context = super(SearchProductView, self).get_context_data(*args, **kwargs) query = self.request.GET.get('q') context['query'] = query return context def get_queryset(self, *args, **kwargs): request = self.request method_dict = request.GET query = method_dict.get('q', None) que = query.split(', ') for query_item in que: if query_item is not None: return Product.objects.search(query_item) -
How to safely increment database using django rest framework?
I'm facing some troubles by trying to make a like/unlike system for my app. It's okay when i like/unlike in a normal timelapse, but when i click multiple times in a very short frequency (20 clicks in 10 seconds for example) then my counter is disturbed. Normally while i'm testing my counter should always have a value of 1 or 0 since i am the only one to do the operation. However when i click quickly and multiple times, my rest api cannot follow the rythm and i'm getting a counter that have 7 or 8 likes. I've tried multiple solutions. first by adding the model transaction included with django. As a decorator : @transaction.atomic Or manually : with transaction.atomic(): #do stuff I've also tried to increment directly from the database by using F() : votes=F("votes") + 1 Nothing seems to work. Any suggestion ? -
Django - CreateView fails, am redirected to empty create view
My CreateView seems to be failing but I am unsure as to why. I am being redirected to an empty CreateView with no errors or messages to tell me why its failing. I would of thought I would of been redirected to CreateView with the entered Data saved and an error. I've checked admin for the model and the record is not being created. the issue seems to be server side but I am not getting any output in console I just get 200s "POST /sites/site/add_subnet/7 HTTP/1.1" 200 41406 my forms.py: class AddSubnetForm(forms.ModelForm): class Meta: model = SiteSubnets fields = ['device_data','subnet', 'subnet_type', 'circuit', 'vlan_id', 'peer_desc'] def __init__(self, *args, **kwargs): site_id = kwargs.pop('site_id', None) super(AddSubnetForm, self).__init__(*args) self.fields['circuit'].queryset = Circuits.objects.filter(site_data=site_id) view.py: class AddSubnet(CreateView): form_class = AddSubnetForm template_name = "sites/edit_subnet.html" @method_decorator(user_passes_test(lambda u: u.has_perm('config.add_subnet'))) def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] self.site = get_object_or_404(SiteData, pk=self.site_id) return super(AddSubnet, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("sites:site_detail_subnets", args=(self.site_id,)) def form_valid(self, form): form.instance.site_data = self.site return super(AddSubnet, self).form_valid(form) def get_form_kwargs(self, *args, **kwargs): kwargs['site_id'] = self.site_id return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=self.site_id context['SiteName']=self.site.location context['FormType']='Add' context['active_subnets']='class="active"' return context template: {% block content %} <div class="col-lg-3"> {{ result }} {{ form.errors }} {% if messages %} {% for … -
Contains or in filtering using DRF
I have a simple Blog app, which contains models Entry with ManyToManyField, called tags MODELS class Tag(models.Model): name = models.CharField(max_length=30) class Entry(models.Model): ... tags = models.ManyToManyFiled(Tag) ... I also have a filter class django_filters.rest_framework.FilterSet, which should be able to filter entries which contain the only tags that were passed to request or the tags + others. How do I implement this? -
Annotate each result with value indicating if minimum or maximum of field
I have two models, Author and Book: class Author(models.Model): name = models.CharField(max_length=256) class Book(models.Model): name = models.CharField(max_length=256) price = models.IntegerField() publication_date = models.DateField() author = models.ForeignKey(Author, related_name="books") Now when I get a set of authors and their books, I want to annotate each book with two values indicating if it is the cheapest or most expensive out of the filtered books from the same author. I got the correct results using Exists and annotations filtered_books = Book.objects.filter(publication_date__year=2010) lower_price = filtered_books.only('id').filter(price__lt=OuterRef('price'), author=OuterRef('author')) higher_price = filtered_books.only('id').filter(price__gt=OuterRef('price'), author=OuterRef('author')) filtered_books = filtered_books.annotate( lowest_price=~Exists(lower_price), highest_price=~Exists(higher_price), ) authors = Author.objects.annotate.prefetch_related(Prefetch('books', queryset=filtered_books)) It works but results in three (lower_price, higher_price and the prefetch) very similar subqueries being executed and is not that fast. How can I optimize it? -
How to create user permissions for my UserPost model.
I'm new to django, i want to know how to assign permissions to the model. My requirement is - i want to create 2 different category posts namely It-posts and Art-posts and need to select any one from the category by the user while signup, after the user login - he must be able to see only the posts that he selected from category, if he tries to select /view the other posts category - a error message should be displayed for the user. I created category while signup but failing in assining permissions for user to see particular posts. Can anyone please help me, how to overcome this issue with this issue.? enter image description here -
How to execute a shell script that prompts user at least 20 times using Python?
I have a shell script that connects to at least 20 remote servers internally using SSH. Therefore, it prompts user to enter password 20 times. I cannot use public authentication key as it can be a security violation. Neither, do I have permissions to install sshpass or any other plugins. I want to learn python and so I want to execute this shell scripts using python that can execute this script and also allow us for user prompts. Further, I want to use Django to make a UI out of the output provided by the shell script. Is that possible and how ? -
Django styling included templates
I have three files. My base.html: {% load static %} <head> <link href="{% static 'base/css/normalize.css' %}" rel="stylesheet" type="text/css" /> <link href="{% static 'base/css/base.css' %}" rel="stylesheet" type="text/css" /> {% block styling %} {% endblock %} </head> <body> {% block content %} {% endblock %} </body> Project.html: {% extends "base/base.html" %} {% load sass_tags %} {% load static %} {% block styling %} <title>Project</title> <link href="{% sass_src 'dashboard/scss/project.scss' %}" rel="stylesheet" type="text/css" /> {% endblock %} {% block content %} <div class="project-container"> {% include "dashboard/tree.html" %}... and tree.html: {% load sass_tags %} <link href="{% sass_src 'dashboard/scss/tree.scss' %}" rel="stylesheet" type="text/css" /> <section class="tree"> <ul class="tree__root">... To summarize above code; project.html extends from base.html, and project.html is also including tree.html. This works as intended and the styling is applied correctly as well. But I'm unhappy about the place of the styling. When I include the styling of tree.html it is put in the body of the DOM. I want it to be in the head. I have tried extending base.html in tree.html and using {% block styling %}, didn't work. Also I tried defining a head in tree.html which didn't work either (no surprise there). So as far as I can see I am left … -
Dynamically Chain Django Forms
In a Django 1.11 app I've created a large form for users to update a model instance, but based on what the users change there may be multiple other forms I'd like to redirect them to afterwards. What's the best practise for dynamically chaining multiple forms (dynamic workflow)? I can't find anything helpful in the Django docs or other questions on here. E.g. (extremely simplified) view for model update form: def asset_edit(request, pk): asset = get_object_or_404(Asset, pk=pk) current_location_concat = "{} {} {}".format(asset.location_building, asset.location_room, asset.location_area) if request.method == "POST": form = EditAsset(request.POST, request.FILES, instance=asset) if form.is_valid(): asset = form.save(commit=False) # setting some things... asset.save() new_location_concat = "{} {} {}".format(asset.location_building, asset.location_room, asset.location_area) if current_location_concat != new_location_concat: check_relatives = True # redirect to check_relatives form if asset.equipment_id: if Asset.objects.filter(equipment_id=asset.equipment_id).count() > 1: duplicate_assets = True # redirect to check_duplicates form # if check_relatives and duplicate_assets: # redirect to check_duplicates form and then on to check_relatives form return redirect("asset_detail", pk=asset.pk) I know I could just add a new URL for my check_duplicates form with a "Next" (or similar) parameter, pass the name of my check_relatives view or a value to map to it or something similar, but is this best practise? Especially given that the … -
cannot upload files to django rest framework using react js
I'm using react Js to upload an image to django restframework. here I'm sending post request using fetch API. Eapp.jsx import React, { Component } from 'react'; class Eapp extends Component { constructor(props){ super(props); this.state = { profilePic: null, }; this.inpuElement = null; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(e){ this.setState({profilePic: e.target.files[0]}); } handleSubmit(){ let formData = new FormData(); formData.append('profile_pic',this.state.profilePic); fetch('http://10.42.0.1:8000/auth/profile-pic/', { method: 'POST', headers: { Accept: 'application/json, text/plain, */*', 'content-type': 'multipart/form-data', }, body:formData, }).then(res => res.json()) .then((data) => { console.log(data); }) .catch(err => console.log(err)); } render(){ return( <div> <input type="file" multiple={false} ref={(input) => { this.inpuElement = input; }} accept=".jpg,.jpeg,.png" onChange={this.handleChange} /> <button onClick={this.handleSubmit}>submit</button> </div> ); } } export default Eapp; error msg Eapp.jsx:19 POST http://10.42.0.1:8000/auth/profile-pic/ 500 (Internal Server Error) handleSubmit @ Eapp.jsx:19 callCallback @ react-dom.development.js:542 invokeGuardedCallbackDev @ react-dom.development.js:581 invokeGuardedCallback @ react-dom.development.js:438 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:452 executeDispatch @ react-dom.development.js:836 executeDispatchesInOrder @ react-dom.development.js:858 executeDispatchesAndRelease @ react-dom.development.js:956 executeDispatchesAndReleaseTopLevel @ react-dom.development.js:967 forEachAccumulated @ react-dom.development.js:935 processEventQueue @ react-dom.development.js:1112 runEventQueueInBatch @ react-dom.development.js:3607 handleTopLevel @ react-dom.development.js:3616 handleTopLevelImpl @ react-dom.development.js:3347 batchedUpdates @ react-dom.development.js:11082 batchedUpdates @ react-dom.development.js:2330 dispatchEvent @ react-dom.development.js:3421 example:1 Failed to load http://10.42.0.1:8000/auth/profile-pic/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500. … -
create several pdf files and compress them for download
I have one problem about download zip file with several pdf file, and in my case I have only links for these pdf files, and I don't know how to it, because in many links which I saw tell me that I just need to show directory, but for my case it doesn't work. I have function for generate pdf file and download it: def get_pdf_document(request, code): host = request.scheme + "://" + request.META["HTTP_HOST"] uri = reverse('documents:view_signed_document', kwargs={'code': code}) + "?is_pdf=true" obj = get_object_or_404(DownloadCode, code=code) options = { 'page-size': 'A4', 'encoding': "UTF-8", 'no-outline': None, 'margin-bottom': '17', 'margin-left': '10', 'margin-right': '10', 'margin-top': '10', 'footer-html': host + reverse('api:pdf-footer', kwargs={'code': code}), } if obj.doc_type == ACTS_TYPE or obj.doc_type == LISTS_TYPE: options['orientation'] = 'Landscape' result = pdfkit.from_url(host + uri, False, options=options) response = HttpResponse(result, content_type='application/pdf') if obj.doc_type == INVOICE_TYPE: doc = proxy.get_invoice_by_id(invoice_id=obj.doc_id, tin=obj.tin) if doc.status.code != pb.ResponseStatus.OK: doc = proxy.get_invoice_draft_by_id( invoice_draft_id=obj.doc_id, tin=obj.tin) doc_num = u"#{}".format(doc.invoice.num) doc_create_date = doc.invoice.turnover_date else: ref = perm.document_type_proxy[obj.doc_type] doc = ref['get'](doc_id=obj.doc_id, tin=obj.tin) if doc.status.code != pb.ResponseStatus.OK: return render(request, 'documents/doc_not_found.html', {'code': code}) doc_num = ("" if obj.doc_type == RECONS_TYPE else u"#{}".format(doc.document.act_num) if obj.doc_type == ACTS_TYPE else u"#{}".format(doc.document.num)) doc_create_date = doc.document.create_date response['Content-Disposition'] = ( "attachment; filename*=utf-8''" + urllib.quote((u'{} - OT {} - … -
Using both the project level and the app level static files in django
I have some static files that will remain common through all the application and I also have some static files that are specific to some particular apps only. Now in one of my apps, i want to use both the project level and the app level static files but that doesn't seem to work. Following code section is from settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "homepage","static"), os.path.join(BASE_DIR, "landing_page","static"), os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I have used python manage.py collectstatic and it returns with a warning which goes like Found another file with the destination path 'homepage\css\style.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Despite the above warning, I still get both the project level and the app level static files in the staticfiles folder in my root directory. When I use it in a template, the project level static file gets loaded while the app level static file (which is just a single CSS file) doesn't get loaded. Following is how I am trying to load the CSS file. {% load static %} <link rel="stylesheet" … -
Django Forms custom error message in views
This is my view: if request.method == 'POST': form = TeacherRegister(request.POST) #Gets school object from email domain. email = form['email'].value().split('@')[1] try: school = School.objects.get(email_domain = email) except ObjectDoesNotExist: #add custom error message here if form.is_valid(): user, Teacher = form.save() Teacher.school = school Teacher.save() user.groups.add(Group.objects.get(name='Teacher')) #user.is_active to stop users logging in without confirming their emails user.is_active = False user.save() #Sends confirmation link. send_confirmation_email(request, user) args = {'email': user.email, 'link': user.Teacher.school.email_website} return render(request, 'email/token_sent.html', args) else: args = {'form': form,} return render(request, 'users/teachers.html', args) These lines are what I am trying to work with: email = form['email'].value().split('@')[1] try: school = School.objects.get(email_domain = email) except ObjectDoesNotExist: #add custom error message here This is the HTML I have for the email field: <div class="required field" > {{ form.email.label }} {{ form.email }} {{ form.email.help_text }} <!-- <label>Email</label> <input placeholder="Email" type="email" name="email" autofocus="" required="" id="id_email"> --> </div> How can I get it to say, if no school object is returned, something along the lines of 'School not found, check your email'? Thanks -
Django - string primary key - get_absolute_url() result in no reverse match
I want to replace the default numeric primary_key with a string. This model was working fine with id, now I recreated it with prg and it fail in retrieving data URL. class Mymodel(models.Model): #id = models.AutoField(primary_key=True) prg = models.TextField(primary_key=True, unique=True) def get_absolute_url(self): # return reverse('label_app.views.label_detail', args=(self.pk,)) return reverse('label_detail', kwargs={'prg': self.prg}) lib/python3.5/site-packages/django/urls/resolvers.py in _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs) 495 "a valid view function or pattern name." % {'view': lookup_view_s} 496 ) --> 497 raise NoReverseMatch(msg) 498 499 NoReverseMatch: Reverse for 'model_detail' not found. 'model_detail' is not a valid view function or pattern this is the prg format: 'Number/number/number' from werkzeug I see: django.urls.exceptions.NoReverseMatch django.urls.exceptions.NoReverseMatch: Reverse for 'Model_detail' with arguments '('180036/10/1',)' not found. 1 pattern(s) tried: ['(?P[\w]+)/modeldetail/$'] what am I doing wrong? Thanks, BR -
django-rest-framework browsable API doesn't show login link
I am currently following the django-rest-api tutorial. In my urls.py, I created the urlpatterns like this: urlpatterns = format_suffix_patterns([ ... url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')), ]) Now when i call any restricted endpoint in my browser, like 127.0.0.1/rest/api/foobar, I get the Browsable API with a 403 Forbidden, which is totally fine. But there is no login link in the top right corner. Why is that? What am I doing wrong? -
Django 1.11 best to approach to "quarter" logic for multiple purposes
I have a Survey app that includes a Survey model and a Response model. class Survey(models.Model): name = models.CharField(max_length=400) is_published = models.BooleanField() class Response(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) survey = models.ForeignKey(Survey, related_name="responses") I also have an admin view for displaying all users, and displaying the latest response a user has submitted class UserAdmin(admin.ModelAdmin): list_display = ('username', 'latest_response') def latest_response(self, obj): return obj.response_set.latest('created') I only have one Survey which I will release for Response every quarter. Currently, the UserAdmin view's latest_response returns the name of the Survey (charField). What I would like to do is use the Response's created or updated (whichever is latest) and, in the UserAdmin, display this as "Q1 2018" for example. I know this can be achieved relatively easily through Django 2.0 using the Date Function extract, but how would I do this using Django 1.11? -
Djagno admin add custom filter
i'm using django 1.10 and i need to display data and create a filter based on a value from a different model(which has a foreign key referencing my model that is used on the admin template) These are my 2 models: This one is used to generate the template: class Job(models.Model): company = models.ForeignKey(Company) title = models.CharField(max_length=100, blank=False) description = models.TextField(blank=False, default='') store = models.CharField(max_length=100, blank=True, default='') phone_number = models.CharField(max_length=60, null=True, blank=True) This is the other one that holds a foreign key reference to my first one: class JobAdDuration(models.Model): job = models.ForeignKey(Job) ad_activated = models.DateTimeField(auto_now_add=True) ad_finished = models.DateTimeField(blank=True, null=True) Inside my template i have been able to display the(latest)start and end times def start_date(self,obj): if JobAdDuration.objects.filter(job=obj.id).exists(): tempad = JobAdDuration.objects.filter(job=obj).order_by("-id")[0] return tempad.ad_activated And then i just call this inside the list_display and that is working fine. However i have trouble setting a filter field using this criteria. If i just add it to my list_filter then i get an error that there is no such field inside my model which is true (since that one is in another table that has reference to my job table). So i was wondering what is the right approach to solve this? Do i need … -
Django - init object has no attribute 'kwargs'
I am trying to filter a forms foreign key like in this post set variable into queryset of forms.py from my generic view or url However I am getting the error 'AddSubnet' object has no attribute 'kwargs' when I remove def init function then the issues are resolved. so I know its definitely something to do with this function but I'm not sure what. full trace: Traceback: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view 62. self = cls(**initkwargs) File "/itapp/itapp/sites/views.py" in __init__ 1001. site_id = self.kwargs['site_id'] Exception Type: AttributeError at /sites/site/add_subnet/7 Exception Value: 'AddSubnet' object has no attribute 'kwargs' views.py: class AddSubnet(CreateView): model = SiteSubnets template_name = "sites/edit_subnet.html" fields = ['device_data', 'subnet', 'subnet_type', 'circuit', 'vlan_id', 'peer_desc'] exclude = ['site_data'] @method_decorator(user_passes_test(lambda u: u.has_perm('config.add_subnet'))) def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] self.site = get_object_or_404(SiteData, pk=self.site_id) return super(AddSubnet, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("sites:site_detail_subnets", args = (self.kwargs['site_id'],)) def __init__(self, *args, **kwargs): #site_id = kwargs.pop('site_id') site_id = self.kwargs['site_id'] self.fields['circuit'].queryset = Circuits.objects.filter(site_data=site_id) def get_form_kwargs(self, *args, **kwargs): kwargs = super(AddSubnet, self).get_form_kwargs() if kwargs['instance'] … -
Accidentally created a file(s) in my remote server and can't get rid of it
. The file(s) I want to remove are ystemctl restart gunicorn. I must have accidentally created this whilst writing systemctl restart gunicorn. Any idea how I can remove these. I've already tried: rm ystemctl which returns No such file or directory rm ystemctl restart gunicorn returns the same error. -
Django file upload for different apps within a project ?
I am working on a project which have various apps like protocol, prediction etc. to perform some calculation "protocol" and "prediction" apps requires user input in the form of file upload. I have implemented the bellow schema which uploads file successfully into the "media" directory which is present at the base project directory. I want to implement file upload in this way so that It can upload file for respective app directory rather a common media directory. My code was like this: Views.py def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) print uploaded_file_url return render(request, 'protocol/submit_job.html', {}) return render(request, 'protocol/main_protocol.html') urls.py url(r'^protocol/$', views.simple_upload, name='simple_upload'), html <form method="post" enctype="multipart/form-data"> <div class="heading"> <h1> Machine Learning Modeling.. </h1> <h2> Upload CSV files .. </h2> </div> {% csrf_token %} <input class="input" type="file" name="myfile"> <button class="button" type="submit"> Upload file and submit job </button> </form> {% if uploaded_file_url %} <p class="text" >File uploaded successfully. </p> {% endif %} this schema work for me and upload all the file into media directory.. What changes should I make to upload file in app specific manner. for example: prediction/Input/uploaded_file_1.csv protocol/Input/uploaded_file_2.csv