Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: type object 'BdsStatusStep' has no attribute '_default_manager'
Trying to write some simple unit tests and getting this error, which I'm totally stuck on: Traceback (most recent call last): File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/django.py", line 140, in _get_manager manager = model_class.objects AttributeError: type object 'BdsStatusStep' has no attribute 'objects' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/loc/tnt/leg_apps/etl/transfers/tests/test_action.py", line 37, in setUp self.first_session_bds_step = BdsStatusStepFactory(action_date_1=datetime.date(2000, 1, 3)) File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/base.py", line 67, in __call__ return cls.create(**kwargs) File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/base.py", line 594, in create return cls._generate(True, attrs) File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/base.py", line 519, in _generate obj = cls._prepare(create, **attrs) File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/base.py", line 494, in _prepare return cls._create(model_class, *args, **kwargs) File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/django.py", line 176, in _create manager = cls._get_manager(model_class) File "/home/.virtualenvs/etl/lib/python3.5/site-packages/factory/django.py", line 144, in _get_manager manager = model_class._default_manager AttributeError: type object 'BdsStatusStep' has no attribute '_default_manager' The line generating the error is a simple instantiation of a BdsStatusStepFactory: self.first_session_bds_step = BdsStatusStepFactory(action_date_1=datetime.date(2000, 1, 3)) which is defined as: class BdsStatusStepFactory(factory.django.DjangoModelFactory): class Meta: model = BdsStatusStep I'm not sure what else I should be looking for. The BdsStatusStep model is quite large and I hesitate to post the whole thing, although I can if it's helpful (or maybe there's something specific I should look for?) Other SO questions about this error seem … -
Calling local api on a server from a hosted website
I'm currently hosting a website and I'm trying to call an API on a remote server. This remote server has a website running locally, and I'm trying to call a certain API from my website to the remote server's localhost. Is something like this possible, or would I have to host the website on the remote server so it isn't locally hosted. For instance, would something like http://IP_address_of_server_goes_here:8000/get_matching_data/?XXXX be possible to get some data from this localhost? -
django.db.migrations.exceptions.NodeNotFoundError: But migration doesn't exists
I am getting this error but my migration folder doesn't even have what it says basket.0002_auto20140827_1705`. The error django.db.migrations.exceptions.NodeNotFoundError: Migration basket.0002_auto20140827_1705 dependencies referene nonexistent parent node (u'partner', u'0001_initial') I do have two subapp - one is oscar, the other is myapp. In myapp, there is migrations folder but nowhere has this basket.0002_auto20140827_1705. I tried looking at oscar's subapp and I don't see any migrations folder anywhere. Where is this error referencing to? -
Django REST: Clear way to serialize two or more levels of nested elements
I have an endpoint, that must return the body, that you can see below: { "item": { "id": 25, "title": "icecream", "description": null, "image_link": null, "measure_units": [ { "id": 67, "unit": { "id": 1, "code": "BX", "title": "Box" }, "quantity": 1000 } ], "created_at": "2017-10-23T11:28:35.534670Z", "updated_at": "2017-10-23T18:28:34.754016Z", "deleted_at": null } } As you can see, I have a separate model mesure_unit, that connects to item with additional Many-to-Many model MeasureItem, where I can define item, measure_unit and set quantity. And as you can see in example body, that makes two level nested objects in measure_units. Below you can see, how I serializing and return all that funny staff. And my question is: is that code optimal? Or I can do something better? Cause I think that my code is not so good as it can be... Serializer: from rest_framework import serializers from .models import Item, MeasureItem from measure_unit.models import MeasureUnit from supplier.models import Supplier class MeasureUnitSerializer(serializers.ModelSerializer): class Meta: model = MeasureUnit fields = ('id', 'code', 'title') class MeasureItemSerializer(serializers.ModelSerializer): class Meta: model = MeasureItem fields = ('id', 'unit', 'quantity') class ItemSerializer(serializers.ModelSerializer): measure_units = MeasureItemSerializer(source='measureitem_set', many=True) supplier = SupplierSerializer() class Meta: model = Item fields = ( 'id', 'title', 'description', 'image_link', 'measure_units', … -
displaying image using django and html
I'm not sure what I'm doing wrong, but my image won't display HTML: {% load static %} <img src="{% static 'images/IMG_0096.JPG' %}" alt="Mountain View"/> settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) Thanks -
Mofidy createView so as to post to two different forms from same template?
I have two models which have common fields, say class model1(models.Model): commonfield1 = ... commonfield2 = ... class model2(models.Model): commonfield1 = ... commonfield2 = ... extrafields=.. .... Now i have two different create forms for these both models using forms.ModelForm. Now, my requirement is that when I create a new object for model2, I also want to save an object in model1. As of now I am using CreateView to save the form for model2. I want to give user an option such that if he presses that save two objects button both the models should be updated accordingly. Is there anyway I can do this using CreateView. -
Calculate due date in django
I am creating a "library" website using django. Once a user has issued a book, I want to calculate a due date for it, 3 months after the issue/present date. How do I do it? -
Django how to see urls.py and settings.py changes without apache restart
I am setting up a django project on an apache server. I have access to the .htaccess and index.fcgi files, but no sudo access. When I make changes to urls.py or settings.py, the changes don´t come through. Is there a way to see changes come through without restarting apache? For example by adding a configuration to the .htaccess file? Here https://stackoverflow.com/a/6282363/5881884 is recommended doing touch on the .wsgi file, but I don´t have any file ending with .wsgi and neither is there a file including the string django.core.handlers.wsgi.WSGIHandler() .htaccess file: AddHandler fcgid-script .fcgi RewriteEngine On RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$ RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$ RewriteRule /static/ /home/myusername/public_html/static RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$ RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$ RewriteRule ^(.*)$ index.fcgi/$1 [L] RewriteCond %{HTTPS} !=on RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$ RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$ RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/[0-9a-zA-Z_-]+$ RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] -
Migration not working Django, Heroku
I have run locally make migrations and I got my migrations files in my folder. Then I pushed it live to heroku. But heroku didn't apply the changes to my database which is causing now an error. One column does not exist because of the missing migration. Locally everything works fine. I checked via heroku bash if the migration files exist and they do. Then I tried to run manage.py migrate. The output was: No migrations to apply. Also having release: python manage.py migrate in my procfile didn't help either. Any ideas what I can try to do else or why heroku is not migrating? -
how to find result with any word in list in django
I would like to find a list of results that are contained that match any word in a list. For example if company have different inputs it could still find them: company_name = 'awesome blossom' I would like to search for companies with 'awesome' and 'blossom' in the name. I tried something like this: companies = Company.objects.filter(company_name__icontains__in=company_name.split(' ') but this didn't work. How can I accomplish this? -
How to handle a form not tied to a specific URL with a view in Django?
I am creating a job board site and I have the following urls.py (not that important just included them to make the question clearer) : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name = "index"), url(r'^job_info/(?P<job_id>[0-9]+)/$', views.job_info , name = "job_info"), url(r'^employer_signup', views.employer_signup, name="employer_signup"), url(r'^employer_home', views.employer_home, name = "employer_home"), url(r'^login/$', login, {'template_name':'core/employer_login.html'}, name = 'employer_login'), ] I have a base.html that is included in all of the HTML files. This includes a Navbar with an inline search bar: <form class="form-inline my-2 my-lg-0 navbar-toggler-right" method = "post" > {% csrf_token %} <input class="form-control mr-sm-2" type="text" placeholder="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> Is there a way to handle this form with a View? As it is not directly tied to any specific URL? -
Bootstrap Snippet does not look like it has to in Django
Heyho, i'm new to Django and i have a problem including a template to my view. I want to use the following snippet from Bootstrap "https://bootsnipp.com/snippets/Nj4gp", but it just look like on the picture below. I took the same Code and just changed the Content of the table. Can somebody tell me what could be wrong, i checked, that bootstrap is in the right static folder. I do not understand why some parts work and others not.enter image description here Thanks in advance! Magda -
DetailView Shows Same Page Doesnt Return Detail page
models.py from django.db import models class india(models.Model): name = models.CharField(max_length=50) body_1 = models.TextField() body_2 = models.TextField() title_img = models.ImageField(upload_to="images/") img_1 = models.ImageField(upload_to="images/") img_2 = models.ImageField(upload_to="images/") img_3 = models.ImageField(upload_to="images/",blank=True) img_4 = models.ImageField(upload_to="images/",blank=True) Date_of_Publishing = models.DateField() Author = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = "Indians" class Australia(models.Model): name = models.CharField(max_length=50) body_1 = models.TextField() body_2 = models.TextField() title_img = models.ImageField(upload_to="images/") img_1 = models.ImageField(upload_to="images/") img_2 = models.ImageField(upload_to="images/") img_3 = models.ImageField(upload_to="images/",blank=True) img_4 = models.ImageField(upload_to="images/",blank=True) Date_of_Publishing = models.DateField() Author = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = "Australians" class South_Africa(models.Model): name = models.CharField(max_length=50) body_1 = models.TextField() body_2 = models.TextField() title_img = models.ImageField(upload_to="images/") img_1 = models.ImageField(upload_to="images/") img_2 = models.ImageField(upload_to="images/") img_3 = models.ImageField(upload_to="images/",blank=True) img_4 = models.ImageField(upload_to="images/",blank=True) Date_of_Publishing = models.DateField() Author = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = "South_Africans" class England(models.Model): name = models.CharField(max_length=50) body_1 = models.TextField() body_2 = models.TextField() title_img = models.ImageField(upload_to="images/") img_1 = models.ImageField(upload_to="images/") img_2 = models.ImageField(upload_to="images/") img_3 = models.ImageField(upload_to="images/",blank=True) img_4 = models.ImageField(upload_to="images/",blank=True) Date_of_Publishing = models.DateField() Author = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = "England's" views.py from django.shortcuts import render from .models import india,Australia,South_Africa,England def index(request): return render(request, "index.html") def india_v(request): rec_posts1 = india.objects.order_by('-Date_of_Publishing')[0:1] rec_posts2 = india.objects.order_by('-Date_of_Publishing')[1:2] rec_posts3 = india.objects.order_by('-Date_of_Publishing')[2:3] post = india.objects.all() context = {'rec_posts1':rec_posts1,'rec_posts2':rec_posts2,'rec_posts3':rec_posts3,'post':post} … -
One form for all classes in a model
I have a parts app where my model looks like this class Part(models.Model): name = models.CharField(max_length=550) def __str__(self): return self.name class Image(models.Model): image = models.FileField() part = models.ManyToManyField(Part, related_name='image_part') class IDNum(models.Model): IDNum = models.CharField(max_length=50) part = models.ForeignKey('Part', related_name='ID') def __str__(self): return self.IdNum class Stock(models.Model): quantity = models.DecimalField(max_digits=10, decimal_places=2) unit = models.ForeignKey('Unit') part = models.ForeignKey('Part', related_name='stock') stockarea = models.ForeignKey('StockArea') class Warehouse(models.Model): name = models.CharField(max_length=550) address = models.TextField() def __str__(self): return self.name class StockArea(models.Model): area = models.CharField(max_length=550) warehouse = models.ForeignKey('Warehouse') def __str__(self): return '%s %s' % (self.warehouse, self.area) class Unit(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=550) abbreviation = models.CharField(max_length=10) def __str__(self): return self.abbreviation In the admin page I have a form for each class. I really want to add a Part and choose Images, set a IDNum, Choose Warehouse to get list of StockArea's for that Warehouse and set Stock Quantity and choose Abbreviation in one form. Is it possible to create a custom form for the admin pages, so that I can manage this for all classes in a model. They are all related somehow. I would like some tips on how, if it's possible =) -
Django using .get fails on model which uses content types
My .get method is failing. From the django documentation on a model implementing content types / generic foreign key you cannot use: TaggedItem.objects.filter(content_object=guido) # This will also fail >>> TaggedItem.objects.get(content_object=guido) So, do I pass in the content_type and object_id instead? I am using get_object_or_404(TaggedItem, content_type__pk=ct_pk, object_id=pk) and this raises a 404 despite these values beign correct in the database. -
Django - how to sum two Fields of a model? [duplicate]
This question already has an answer here: Django Aggregation: Summation of Multiplication of two fields 4 answers Here's a quick example class Invoice(models.Model): (...) net_amount = models.DecimalField(decimal_places = 2, max_digits=8) tax = models.DecimalField(decimal_places = 2, max_digits=8) @property def gross_amount(self): return self.net_amount + self.tax Then I want to query for chosen Invoices in my ListView using a form and GET: class ListInvoicesView(ListView, FormMixin): (...) def get_queryset(self): (...) return self.model.objects.filter(gross_amount__lte = self.kwargs.get('max_gross_amount')) (I skip some code for the sake of readability) This yields FieldError: Cannot resolve keyword 'gross_amount' into field. What is the proper way to sum two fields of a model? -
Backend endpoints to frontend
Here's the situation: We have a large django application, not on REST structure, our front-end was build with React. What we want to do is find an easy way to tell our front-end which are the URL's that our backend has. For example: Our backend has a "active plan" endpoint which is "plans/active", what we are doing in present days is build a file with django templates that builds an JS object with that endpoints, something like: const urls = {plans: {active: {% url "active_plan" %}}}; The problem here is that it's growing like hell and slowly becoming unorganized and with repeated urls. We had 2 ideas: First one was to parse these urls on python build to generate a file with similar structure as I said before, reflecting exactly what we desire Second one was to have something like a store to make an initial request that is gonna return some area (or all) urls and store these in an object. First one problem is that with an international application, we're gonna have all languages urls in one file, it doesnt not seen nice. Second problem is that we think it can become a big payload if not broken … -
TypeError : encode() missing 1 required positional argument: 'iterations'
i dont know what is triggering this error. i dont know why i keep getting this error . i already change a few parts of code and still i get this error . i have been trying to fix it for 2 days . Traceback: File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adila\Documents\tryFOUR\src\register\views.py" in register 13. user = form.save() File "C:\Users\Adila\Documents\tryFOUR\src\custom_user\forms.py" in save 50. user.set_password(self.cleaned_data["password2"]) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\base_user.py" in set_password 105. self.password = make_password(raw_password) File "C:\Users\Adila\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\hashers.py" in make_password 84. return hasher.encode(password, salt) Exception Type: TypeError at /accounts/register/ Exception Value: encode() missing 1 required positional argument: 'iterations' hashers.py : from django.contrib.auth.hashers import PBKDF2PasswordHasher from django.utils.crypto import (get_random_string, pbkdf2) from honeywordHasher.models import Sweetwords class MyHoneywordHasher(PBKDF2PasswordHasher): algorithm = "honeyword_base9_tweak3_pbkdf2_sha256" iterations = PBKDF2PasswordHasher.iterations*3 def hash(self, password, salt, iterations): hash = pbkdf2(password, salt, iterations, digest=self.digest) return base64.b64encode(hash).decode('ascii').strip() def salt(self): salt = get_random_string() while Sweetwords.objects.filter(salt=salt).exists(): salt = get_random_string() return salt def verify(self, password, encoded): algorithm, iterations, salt, dummy=encoded.split('$',3) hashes = pickle.loads(Sweetwords.objects.get(salt=salt).sweetwords) hash = self.hash(password, salt, int(iterations)) if hash in hashes: return honeychecker.check_index(salt, hashes.index(hash)) return False def encode(self, password, salt, iterations): sweetwords = ['hilman95'] sweetwords.extend(honey_gen.gen(password, base64, ["passfiles.txt"])) … -
How to create a download button/option for image/filefield in Django
Working fine. But whenever i am hitting the file download link download option appears but after i download the file it's no longer the same file that i have uploaded. rather it becomes 9 bytes small file and can't be opened. views.py def download_file(request, path): response = HttpResponse('image/png') response['Content- Type']='image/png' response['Content-Disposition'] = "attachment; filename="+path response['X-Sendfile']= smart_str(os.path.join(settings.MEDIA_ROOT, path)) return response urls.py url(r'^get\/(?P<path>.*)$', download_file), -
Redirect after POST django rest framework
I am submitting a POST request via django form to my Django Rest Framework api. Here is a snippet of my form: <form action="{% url 'entry-list' %}" method="POST" class="form" role="form"> {% csrf_token %} {{form.as_p}} <div class = "form-group"> <button type="submit" class="save btn btn-default btn-block">Save</button> </div> views.py: class entry_ViewSet(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class= EntrySerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,) def perform_create(self, serializer): serializer.partial = True serializer.save(created_by=self.request.user) I am making a successful POST (and item is created in database), however once I save I go to the url /api/entry/ which shows my api w/Markdown. I'd like to have it go back to a specific url. Is there a way to customize where the POST redirect to if successful? -
Django : several models returns in queryset
Yeah I know, it's not possible. Or maybe I didn't see. But, I'm gonna explain why I need this. Let's do some dummy classes: class A(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() lvl_struct = GenericForeignKey('content_type', 'object_id') Let's say A can be attached to a struct (logical struct, like department in jobs). An A instance can be attached to only one struct, but there're 4 disctinct type of struct, and that's where I discovered generic foreign key (instead of a polymorphism on A). But now, my problem is, in my form, I want to attach the actual struct when I create a A instance : class CreateAForm(forms.ModelForm) lvl_struct = forms.ModelChoiceField( queryset=None, #here is my problem required=True ) So here I would like to have a unique select with all possibilities (all instances of first struct type, all instances of second struct type and so on). So is there any way to do this, or will I have to do like four select with some js to check at least one and only one select has a value? Or of course a third solution which I didn't see. Tell me. Thank you in advance for your time. -
How to introduce a model class method in Django admin
I have a model that has class methods. In testing the class methods work and alter the model instances according to my needs. The issue is using this class method in the admin. When an application cannot pay a late payment fee is applied creating another transaction altering the balance. The method in models is decorated with a @classmethod decorator. I need to get it so when status is altered, or when a tickbox is checked in the admin for an application it fires the class method. I have Googled overriding models in admin but cannot find anything. Many thanks for reading this. -
Replace string with other string python django
Hi guys i want to convert link into proper format for example i have text like This is google link https://www.google.com This is gmail link https://www.gmail.com And what i want is This is google link <a href="https://www.google.com">https://www.google.com</a> This is gmail link <a href="https://www.gmail.com">https://www.gmail.com</a> and here is code that i have written body_without_quotes = request.POST.get('stripped-text', '') data1 = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', body_without_quotes) for da in data1: link = "<a href="+da+">"+da+"</a>" body_without_quote = body_without_quotes.replace(da, link) print body_without_quotes but it does not print required output can anyone tell me what i am doing wrong here. Thanks -
Django: How to return with context from UpdateView (CBV)?
The following view works as expected class BrandEditView(PermissionRequiredMixin ,generic.UpdateView): permission_required = 'change_brand' template_name = 'brand_update_form.pug' model = Brand fields = ['name'] def get_object(self, queryset=None): print(self.request.user) self.object = Brand.objects.get(id=self.kwargs['pk']) obj = Brand.objects.get(id=self.kwargs['pk']) return obj After form submission, how do I return to the same view (with the same object), but with a message like "brand edited successfully"/"you can't do that"? I've found a way to redirect to the same view, but not with context. -
Performance, load and stress testing in Django
I am studying the different types of testing for a Django application. I know how to do functional and unit testing in Django and how to apply different methodologies, but now I am facing a new challenge, I need to know how to do: Performance testing Load testing Stress testing I know the difference between them but I dont know which is the best methodology to follow,which are the best packages for do it or simply where I can get some documentation about it. So my question is, how can I start to do these types of tests in a Django app or where can I get some good documentation about it? Thanks