Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why django timesince is not working?
I am trying to use timesince from django but I want it shows "semana" instead of "week", as far as I knew we just need to set 2 things in settings and it should work >>> from django.conf import settings >>> settings.USE_I18N True >>> settings.LANGUAGE_CODE 'pt-br' >>> timesince(datetime.now() - timedelta(days=7)) u'1 week' What is wrong here? -
TypeError: <class 'loanwolf.customers.forms.CustomerSignupForm'> is not JSON serializable
I am trying to understand an error I got with this class : class CustomerSignupForm(SignupFormOnlyEmail): def clean_email(self): email = super(CustomerSignupForm, self).clean_email() """ Validate that the e-mail address is unique. """ # raise forms.ValidationError(_('This email is already in use. Please supply a different email.')) return email def __init__(self, *args, **kwargs): #self.fields['language'].help_text = '' self.helper = FormHelper() self.helper.form_class = 'row' self.helper.form_method = 'post' self.helper.form_action = '.' self.helper.form_id = 'customer-signup-form' self.helper.layout = CustomerSignupLayout super(CustomerSignupForm, self).__init__(*args, **kwargs) The traceback is Traceback (most recent call last): File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 170, in __call__ response = self.get_response(request) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 140, in get_response response = self.handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 234, in handle_uncaught_exception return handle_uncaught_exception(request, resolver, exc_info) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django_extensions/management/technical_response.py", line 6, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 131, in get_response response = middleware_method(request, response) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/djdev_panel/middleware.py", line 212, in process_response bits[-2] += debug_payload(request, response, self.view_data) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/djdev_panel/middleware.py", line 86, in debug_payload cls=LazyEncoder)) File "/usr/lib/python2.7/json/__init__.py", line 251, in dumps sort_keys=sort_keys, **kw).encode(obj) File "/usr/lib/python2.7/json/encoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode return _iterencode(o, 0) File "/home/jeremie/Projects/24-django/venv/lib/python2.7/site-packages/djdev_panel/middleware.py", line 34, in default return … -
Django case insensitive "distinct" query
I am using this django query people.exclude(twitter_handle=None).distinct('twitter_handle').values_list('twitter_handle', flat=True) My distinct query is returning two objects For example : ['Abc','abc'] How can i get case insensitive results ? like in this case only ['abc'] using django 1.9.6, python 2.7 -
Best practices for using Django ORM in threaded application
I'm working on a multi-threaded application that uses the Django ORM with MySQL. The idea is to use a single startup script to launch multiple modules ("module" here in the functional sense, not the literal Python sense), each of which has a "service loop" that runs in its own thread. I've organized it using a single class for each module. I originally did this using a sqlite DB and it worked great. Now I'm transitioning to MySQL and am running into DB connection problems related to threading. For example, it looks like I need to call db.connections.close_all() within each thread to avoid contention with the DB connection? I'm thinking that I need to move all setup related to the Django ORM to the service thread but then I wouldn't be able to import models in the class's init() method. Anyway, I'm sure that other people have dealt with this before, and I'm sure there are some good patterns out there. Anyone have any suggestions or best practices they could share? This is my simple startup script: from controller.modules.manager import Manager from controller.modules.scanner import Scanner print("Starting...") # The directory scanner scanner = Scanner() # The job manager manager = Manager() And … -
Why do I get different results if I use first() vs last() on a QuerySet with the length of 1
while writing a testcase for a method I discovered that I get different results if I use my_queryset.first().my_annotated_value than when I use my_queryset.last().my_annotated_value although my_queryset.count() returns 1. Here is the relevant code snippet: class ShopManager(models.Manager): def get_best_matches(self, customer): shops = super(ShopManager, self).get_queryset().filter(employees__matches__customer=customer).annotate(max_match_percentage=Coalesce(Max('employees__matches__match_value'), 0)).order_by('-max_match_percentage') for shop in shops: shop.max_match_percentage = float(shop.max_match_percentage) * 100.0 return shops In the shell I run: shops = Shop.objects.get_best_matches(customer=Customer_A) shops.count() # returns 1 shops.first().max_match_percentage # returns 73.9843 shops.last().max_match_percentage # returns Decimal('0.739843') I have different django apps for shops, matches, employees and customers. I searched for hours and checked the implementation for first() and last() in the django docs. I could not find anything that explains this behavior. Why are the values different, what exactly is happening? Am I doing something wrong or is this a bug? -
value from select row material-ui-datatable React
i need get value from a cell in selected row this my table <DataTables height={'auto'} selectable={true} showRowHover={true} filterHintText ={this.props.filtro} title = {this.props.titulo} showHeaderToolbar={true} columns={TABLE_COLUMNS} data={this.state.data} showCheckboxes={true} onRowSelection={this.handleRowSelection} onFilterValueChange={this.handleFilterValueChange} onSortOrderChange={this.handleSortOrderChange} enableSelectAll={true} page={1} count={100} />); and this is my method handleRowSelection(selectedRows) { console.log('Valor: ' + selectedRows); } and just get a row id, i dont know how get cell data from selected row i try this form but results undifinded console.log('Valor: ' + selectedRows[1]); -
OperationalError when trying to get the url page
I am trying to get an url that contains some data from my database, but I keep getting this error: self = <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x7f01c35c2d38> query = ' SELECT cust.id, cust.name, inv.currency_id, SUM(inv.total)\n FROM\n v3_customer as cust\n ... and inv.invoice_date < ?\n GROUP BY cust.id, inv.currency_id\n ORDER BY cust.id, inv.currency_id' params = [(1,), '2016-12-04'] def execute(self, query, params=None): if params is None: return Database.Cursor.execute(self, query) query = self.convert_query(query) > return Database.Cursor.execute(self, query, params) E sqlite3.OperationalError: near "?": syntax error ../../../environments/tracerenv/lib/python3.4/site-packages/django/db/backends/sqlite3/base.py:337: OperationalError This is my code: response = admin_client.post( reverse('report_create') + '?report_type=1', { 'start_date': datetime.datetime.now().date() - datetime.timedelta(days=180), 'end_date': datetime.datetime.now().date() + datetime.timedelta(days=180), } ) print(admin_client.get(Report.objects.first().get_absolute_url())) -
Django Rest Framework Model relationships
I have a selection of models to make adverts for retailers using different products, templates and sizes: Retailer Template (Foreign Key related to a retailer) Product (Foreign Key related to a retailer) Size (can be attributed to any retailer) Ad (Needs to represent a single product, template, retailer and size) I'm working with the HTML view to create entries. Having created all the entries for Retailers, Templates, Sizes and Products, I would like to create Ads. The problem is that whilst creating a new Ad I don't know how to choose a retailer primarily then limit the choice of template and product to ones that are valid to that retailer. Is it a serializer, view, filter or some sort of validation? -
Count foreign key in django
I am doing some statistics between products and suppliers in django 1.11 with python3, the problem is that I do not know how to relate the model: class Proveedor(models.Model): nombre_empresa = models.CharField(max_length=150) direccion = models.TextField() telefono = models.IntegerField() fecha_registro = models.DateField(auto_now_add=True) def __str__(self): return self.nombre_empresa class Producto(models.Model): nombre_producto = models.CharField(max_length=150) descripcion = models.TextField() precio = models.IntegerField() proveedor = models.ForeignKey(Proveedor) fecha_registro = models.DateField(auto_now_add=True) def __str__(self): return self.nombre_producto With the following sql statement: select nombre_empresa,count(prod.id_proveedor) from productos prod,proveedores prov where prod.id_proveedor=prov.id_proveedor group by nombre_empresa My code : from app.models import Producto,Proveedor productos = Producto.objects.all() # How do I do the filter ? for producto in productos: proveedor = producto.proveedor I need to see the name of the suppliers with the quantity products that each supplier How can I make the same relation to load a list with that result? -
Using context parameter with django-simple-menu
I want to make a menu in my django app that is changing depending on the page that is being viewed. I'm trying to use Django-simple-menu for this. I'm struggeling to get the URL parameters to be accesible in my menus.py. This is the code I have so far and want to replace the 'company' string with a parameter coming from my URL parameters. Is this possible or is it better to create a menu in my views and assign it to the context? hier = Hierachy.get_root_nodes().filter(company__slug= 'company') for site in hier: children = list() for plant in site.get_children(): children.append(MenuItem(plant.name, reverse('pha:companyHierarchy', args=[plant.company.slug, plant.slug,]), weight=10, icon="user")) Menu.add_item("study", MenuItem(site.name, reverse('pha:companyHierarchy', args=[site.company.slug, site.slug,]), weight=10, icon="tools", children=children)) -
Django SQL query duplicated
I have a models.py file containing this: class Entry(models.Model): text = models.TextField(default='') time_created = models.DateTimeField(auto_now=False, auto_now_add=True) time_updated = models.DateTimeField(auto_now=True, auto_now_add=False) created_by = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: abstract = True #rest of code ... class Question(Entry): def get_absolute_url(self): return reverse('view_question', args=[self.id]) class Answer(Entry): question = models.ForeignKey(Question, on_delete=models.CASCADE, default=None) by using django debug toolbar I found out that I am duplacting many SQL queries. What I am trying to do is get the last five questions asked, and display them in my home page, along with some more data containing Answers to those questions, the user who provided the answer, avatar of that user and ... I am currently doing that with this views.py and home.html template: views.py: @login_required(login_url="accounts/login/") def home_page(request): last_five = Question.objects.all().order_by('-id')[:5] last_five_in_ascending_order = list(reversed(last_five)) return render(request, 'home.html', { 'question_list': last_five_in_ascending_order, }) home.html: {% for question in question_list %} <a href="{% url 'view_question' question.id %}">{{ question.text }}</a> {% if question.answer_set.all %} {% for answer in question.answer_set.all %} <img src="/media/{{ answer.created_by.userprofile.avatar }}" alt=""> <a href="{% url 'profile' answer.created_by.id %}"> {% firstof answer.created_by.get_full_name answer.created_by.username %} </a> {{ answer.time_passed }} {{ answer.text | safe }} {% endfor %} {% endif %} {% endfor %} -
Ger parent page on creating new Wagtail Page
I need to change some field default value given a value from the parent page when creating a new page. When editing an existing page, this is not a problem, but when creating a new page, I need to set a default value for a field. I have tried overriding the admin form, on init for WagtailAdminPageForm, the parent_page parameter is empty. And if I try to do it on the init method form Page subclass, there is no arg or kwargs with the parent information. is there a way to get the page for which the new page will be the parent? This is what I tried on Page constructor class CMSPage(Page): . . . def __init__(self, *args, **kwargs): super(BaseContentMixin, self).__init__(*args, **kwargs) if hasattr(self.get_parent().specific, 'published_site') and self.get_parent().specific.published_site == 'extranet': self.published_site = 'extranet' This works editing a page, for new page, I get that NoneType objects has no attribute specific. Django version is 1.10, Python version is 3.6, Wagtail version is 1.9 -
StyleSheet1 instance has no attribute 'fontName' paragraph text u'<para>MARRSISSokpdoskfosdf</para>' caused exception
I am using reportlab, django 1.10 and python 2.7 to generate a pdf and trying to put a paragraph throws this error. The code is this `from reportlab.platypus import Paragraph from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase.pdfmetrics import registerFontFamily def articulo (self,noticia): HSize = A4[1] WSize = A4[0] self.pdfproject.setFillColor(HexColor("#3f39b8")) path = self.pdfproject.beginPath() path.moveTo(0 * cm, 0 * cm) path.lineTo(0 * cm, HSize * cm) path.lineTo(WSize * cm, HSize * cm) path.lineTo(WSize * cm, 0 * cm) self.pdfproject.drawPath(path, True, True) estilo = getSampleStyleSheet() estilo.add(ParagraphStyle(name="ejemplo", fontName="eLinkL",alignment=0, fontSize=12, textColor="white")) parrafo = Paragraph(noticia.contenido,estilo,bulletText=None,encoding='utf8') self.pdfproject.setFont("eLinkL", 12) parrafo.drawOn(self.pdfproject,4*cm, 15*cm)` -
Display a calculated value from models in a template in Django
I want to show the calculated discount under every product. The code below has no errors, but it does not display the value. models.py: from django.db import models # Create your models here. CATEGORIES = ( ('Electronics', 'Electronics'), ('Clothing', 'Clothing'), ) class Products(models.Model): Image = models.FileField() ProductName = models.CharField(max_length = 250, default='') Brand = models.CharField(max_length = 250, default='') OriginalPrice = models.IntegerField(default = '') Price = models.IntegerField(default = '') Category = models.CharField(max_length = 250, choices = CATEGORIES) class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' def DiscountCalc(self): Discount = (Price/OriginalPrice) * 100 return self.Discount def __str__ (self): return self.ProductName This is the template index.html: {% for product in AllProducts %} <article class="product col-sm-3"> <a href="#" class="prodlink"> <img src="{{ product.Image.url }}" class="prodimg img-responsive"> <p class="prodname">{{ product.ProductName }}</p> <span class="origprice">₹{{ product.OriginalPrice }}</span> <span class="price">₹{{ product.Price }}</span> <div class="discount"> <p>{{ product.Discount }}% off</p> </div> </a> </article> {% endfor %} -
Django QuerySet vs. raw SQL performance considerations
I'm learning Django and its ORM data access methodology and there is something that I'm curious about. In one particular endpoint, I'm making a number of database calls (to Postgres) - below is an example of one: projects = Project.objects\ .filter(Q(first_appointment_scheduled=True) | (Q(active=True) & Q(phase=ProjectPhase.meet.value)))\ .select_related('customer__first_name', 'customer__last_name', 'lead_designer__user__first_name', 'lead_designer__user__last_name')\ .values('id')\ .annotate(project=F('name'), buyer=Concat(F('customer__first_name'), Value(' '), F('customer__last_name')), designer=Concat(F('lead_designer__user__first_name'), Value(' '), F('lead_designer__user__last_name')), created=F('created_at'), meeting=F('first_appointment_date'))\ .order_by('id')[:QUERY_SIZE] As you can see, that's not a small query - I'm pulling in a lot of specific, related data and doing some string manipulation. I'm relatively concerned with performance so I'm doing the best I can to make things more efficient by using select_related() and values() to only get exactly what I need. The question I have is, conceptually and in broad terms, at what point does it become faster to just write my queries using parameterized SQL instead of using the ORM (since the ORM has to first "translate" the above "mess")? At what approximate level of query complexity should I switch over to raw SQL? Any insight would be helpful. Thanks! -
Use DRF serializer for django's JSONField?
I'd like to store data which are not always supported by django's default json encoder(?) For instance I have a Price class that has amount and currency. I have a serializer (DRF) for the instances of this class. The data that I'd like to save in the json field looks like the following, price_data = { 'prices': [ 3 : { 'price': Price(30, currency='usd'), 'product_variant_id': 3 }, 5: { 'price': Price(50, currency='usd'), 'product_variant_id': 5 } ], 'seller_prices': [ 8 : { 'price': Price(30, currency='usd'), 'product_variant_id': 8 }, 9: { 'price': Price(50, currency='usd'), 'product_variant_id': 9 } ] } I think I can create a drf-serializer which can serialize/deserialize such data format. Where should I use this serializer though? On my model's __init__() and save() method? or some other place is preferred? -
django unique_together with three fields - unexpected "already exists" error
I'm trying to make inventory system for products like Tyre/Tube. There are many categories like Truck Nylon, Jeep Nylon, Jeep Radial, Car Nylon, Car Radial etc. Under each category, there will be many products with specification names like, 825.20.16, 900.20.14, 135/70R12 etc. For every specifications, there will be different manufactures. Some specifications under Radial type tyres may have two variants Tubed Tyre & Tubeless Tyres. Here's my models. class Category(MPTTModel): name=models.CharField(max_length=75,null=False,blank=False, unique=True) parent=TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) def __str__(self): return self.name PRODUCT_TYPE=(('TL','Tubeless Tyre'), ('TT','Tubed Tyre'), ('NA','Not applicable')) class Product(models.Model): name = models.CharField(max_length=30,null=False, blank=False) category=TreeForeignKey(Category, null=False,blank=False) def __str__(self): return '%s = %s' % (self.name,self.category.name) class Meta: ordering=['category'] **unique_together = ('name', 'category')** class ProductStock(models.Model): product=models.ForeignKey(Product, null=False,blank=False) manufacturer=models.OneToOneField(Manufacturer, null=False,blank=False) product_type=models.CharField(max_length=2, choices=PRODUCT_TYPE,) opening_stock=models.PositiveIntegerField(default=0) def __str__(self): return '%s (%s) stock = %d ' % (self.product, self.manufacturer, self.opening_stock) class Meta: ordering=['manufacturer'] **unique_together = ('product', 'manufacturer','product_type')** Please see the last unique_together. I need to ensure that there won't be any duplicate Tubeless or Tubed-tyre for any manufacturer under any specification. I have added a stock as given below. Car Radials => 135/70R12 Manufacturer: CEAT Type: Tubeless Opening stock: 5 Now, when I try to enter a Tubed-tyre type stock for the above set of parameters, (Car Radials … -
<<MISSING VARIABLE " % s ">> while trying to parse the dictionary object that i passed from a context process
i have a nav bar that should contain the category names and the sub category name. I created a file 'contextprocessor.py' and written the function to return the dictionary object. # contextprocessor.py def test_categories(request): return {'tests':categories} I have written the dictionary in a separate file named 'category.py' and imported it in 'contextprocess.py' # category.py categories = [ { "id": "1", "name":"Men", "url":"/men/", }, { "id": "2", "name":"WoMen", "url":"/women/", }, { "id": "3", "name":"Popular", "url":"/popular/", }, { "id": "4", "name":"New", "url":"/new/", }, ] my base.html looks like this # base.html {% for test in tests %} {{ test.name }} {% endfor %} when i run the page i get a '<< MISSING VARIABLE "test.name" >>' text on browser instead of the name of the categories. Please help ! if i am not accessing the dictionary in a proper way... -
Django: other options than models.TextField() for articles
So in the Django tutorials we make a sparse polls application that shows off some of what Django can do, but leaves a lot to be desired when it comes to learning Django (e.g. using their UserCreationForm to make a user portal). In part of the tutorial they talk about how the admin should be publishing content (e.g. if it were a blog or newspaper) and we set up the admin site where one can make new questions for the polls. In regard to the blog idea - since an article would be lengthy most likely - I think the correct model would include models.TextField. However, looking at Django's naturally generated admin site for adding / modifying new models with a TextField leaves a lot to be desired. What if there should be images embedded among the text? or what if there should be formatted text? The admin site does not support a user friendly way to do this. My question is how to produce a user friendly way for making mixed media e.g. a Stack Exchange post which might have images, code formatting, text formats, etc. -
Cannot create a consistent method resolution: SingleObjectMixin, DeletionMixin
Django 1.11.1 Could you have a look at the traceback. I can't understand what interferes with what in SingleObjectMixin and DeletionMixin. Could you give me a kick here? Traceback: File "/home/michael/PycharmProjects/photoarchive_2/photoarchive/frameplaces/views.py", line 53, in <module> DeleteView): TypeError: Cannot create a consistent method resolution order (MRO) for bases object, SingleObjectMixin, DeletionMixin class FramePlaceDelete(SubmodelDeleteHistoryMixin, DeleteView): model = FramePlace class SubmodelDeleteHistoryMixin(GeneralHistoryMixin, DeletionMixin): operation = "-" # For FramePlaceHistoryMixin. def delete(self, request, *args, **kwargs): # DeleteView differs from CreateView and UpdateView: # it doesn't validate the form. # And we also need the object in save_history(). self.object = self.get_object() super(SubmodelDeleteHistoryMixin, self).save_history() success_url = self.get_success_url() self.object.delete() return HttpResponseRedirect(success_url) -
Django: Is it possible to choose 'how' the help_text gets displayed?
class StudentForm(ModelForm): class Meta: model = Student fields = ['name', 'age', 'courses'] help_texts = { 'age': "enter your age in years and months", 'courses': "select your courses for the current term only" } I have a ModelForm with help_texts and want to display each help_texts in the template only when the user hovers over the info icon (that I have put next to the label in the template). I have achieved that by accessing myfield.help_text in the template and putting it where I want to but Django also puts the help_text just below the input box. Is it possible to tell Django not to do that? Or is it possible to tell Django to change the location of the help_text? The docs dont say much about it. Alternatively, I could just put the helper text in the template directly and not use Django's help_text at all but it feels right to put it in the view itself (since that ideally falls in the 'what data to show' bucket) and the fields labels are also defined in the Form class. Using a separate custom attribute (called hover_text or something) for all fields in the form also seems counter-intuitive since we have … -
Adding docker to django project: no such file or directory
I am trying to add docker support to an already existing django project. I have a Dockerfile, a docker-compose, and a gunicorn.sh which I use as a script to launch the whole things. That script works fine when I run it from my shell. When I run: docker-compose -f docker-compose.yml up I get this error: ERROR: for intranet_django_1 Cannot start service django: oci runtime error: container_linux.go:247: starting container process caused "exec: \"/srv/gunicorn.sh\": stat /srv/gunicorn.sh: no such file or directory" What the hell am I doing wrong? I am very much a docker n00b so any explanation would be most welcome. The Dockerfile looks like so: FROM python:3 ENV PYTHONUNBUFFERED 1 ENV DB_NAME unstable_intranet_django ENV DB_USER django ENV DB_PASSWORD ookookEEK ENV DB_HOST db ENV DB_PORT 3306 RUN groupadd -r django RUN useradd -r -g django django COPY ./requirements/requierments.txt /srv/ RUN pip install -U pip RUN pip install -r /srv/requierments.txt COPY ./intranet_site/ /srv RUN chmod a+rx /srv/gunicorn.sh RUN chown -R django:django /srv USER django WORKDIR /srv I am well aware that the passwords should not be set here and that a permanent volume with a file containing them is probably the best way to deal with it. However, I kinda want something … -
How to post a data with an array field in react request?
So I'm using request from https://github.com/request/request#forms. In tsx file, I'm passing id: id, text: string, array: number[]. post( {json: true, url: '...', form: {id: id, text: text, array: array}}, (error, response, body) => { if (response.statusCode === 400) { dispatch(errStep(body['text'])); } else { dispatch(addStep(body)); } } ) This is a post method with the body {id: id, text: text, array: array}. However, from Django, when I print the request.data, I receive <QueryDict: {'text': ['hello'], 'id': ['12'], 'array[0]': ['51'], 'array[1]': ['52']}> I don't know how to retrieve the array out from this request.data format in Django. I would like my request.data to be in this format: <QueryDict: {'text': ['hello'], 'id': ['12'], 'array': ['51', '52']}> because [51, 52] is returned by calling request.data.getlist('array'). Thanks! -
svn: E155007: '/home/k/python/myproject_env/django-myproject/myproject' is not a working copy
I have been building django project and I want to use Subversion for version control on Ubuntu. As you know, I need to keep most of the projects in the repository, however, some files and directories should only stay locally and not be tracked. So I went to my project directory and typed the following command. svn propedit svn:ignore myproject But exception has occurred like this. svn: E155007: '/home/k/python/myproject_env/django-myproject/myproject' is not a working copy The path is ture that my app is located at /home/k/python/myproject_env/django-myproject/myproject The guide says that when I type the command above, this will open a temporary file in the editor, where I need to put the following file and directory patterns for Subversion to ignore. But it doesn't work. I already found the solution, but there is no answer anywhere. I would like to know the solution. Thanks for your time. -
Passing kwargs to class based view in unittest
I have test like that: def test_getting_delete_view_invokes_point_changes_and_returns_status_200(self, point_changes): request = RequestFactory().get(reverse('questions:delete-help', kwargs={'pk': 1})) view = DeleteHelp.as_view() view.kwargs['pk'] = 1 response = view(request) And my view function: class DeleteHelp(DeleteView, LoginRequiredMixin): model = Help template_name = 'confirm_deletion.html' def get_object(self, queryset=None): return get_object_or_404(Help, pk=self.kwargs['pk'], author=self.request.user) def get_success_url(self): point_pk = self.object.answer_to.plan_point.point_of.id point_changes(point_obj=self.object.answer_to.plan_point) return reverse('plans:display-public', args=[point_pk]) The question is, how am I supposed to pass 'pk' there? I keep getting an error KeywordError 'pk' in get_object method. If I use self.client to access this view then it works (why?), but I want to use RequestFactory. Any help would be appreciated.