Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set user attribute after project creation
In my app A User can create a project by giving it a name. That is my model : class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk}) def __str__(self): return self.name that is my views: class ProjectCreate(CreateView): model = Project fields = ['name'] template_name = 'project_form.html' How can I set when a user create a project project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) with his ID and save it in the DB ?? Thx you -
Regarding displaying titles on blog sites using django and bootstrap
Currently, I am building blog site by using django and bootstrap. In this work, the HTML of the bootstrap theme that I plan to use is a slightly complicated structure, so I am in trouble because I can not display the blog title by the loop in HTML. Regarding solution to this problem, title data stored in an array is retrieved one by one, and embedding tags or variables in HTML, I thought that I could display the title of each article. however, I do not know how to realize it. I think the following code the minimum elements that make up the display of titles in django. What elements should be added besides the below? base.html <body> <div id="content"> {% block content %} {% endblock %} </div> </body> list.html {% block content %} {% for post in posts %} <p>{{ post.title }}</p> {% endfor %} {% endblock %} view.py class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 10 template_name = 't_env/post/list.html' model.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) After removing {% for post in posts%} in list.html, I tried that add filters, arguments, etc. for {{post.title}} would work, but it … -
Django - Custom save method in model
(Using Django 1.11.5) Traditionally, I've always created a model like so: class Animal(models.Model): is_hungry = models.BooleanField(default=True) Then make changes like so: animal = Animal() animal.save() animal.is_hungry = True animal.save() Recently, I saw a friend define a model with a custom save method: class Animal(models.Model): is_hungry = models.BooleanField(default=True) def feed_animal(self): self.is_hungry = False self.save() And calling this method appears to work as expected: >>> from testapp.models import Animal >>> a = Animal() >>> a.save() >>> a.is_hungry True >>> >>> a.feed_animal() >>> a.is_hungry False Are there any benefits/drawbacks in defining such a custom save method in the model definition? Is there any reason to prefer calling .save() on the object directly? -
create_product() missing 1 required positional argument: 'category_id'
I m trying to use related object but i keep getting this error create_product() missing 1 required positional argument: 'category_id' I have been trying to figure out how to fix the error Here is my views def create_product(request, category_id): form = ProductForm(request.POST or None, request.FILES or None) category = get_object_or_404(Category, pk=category_id) if form.is_valid(): category_product = category.song_set.all() for s in category_product: if s.name == form.cleaned_data.get("song_title"): context = { 'category': category, 'form': form, 'error_message': 'You already added that song', } return render(request, 'shop/product/product_create.html', context) product = form.save(commit=False) product.category = category product.save() return render(request, 'music/detail.html', {'category': category}) context = { 'category': category, 'form': form, } return render(request, 'shop/product/product_create.html', context) I m trying to use related object but i keep getting this error create_product() missing 1 required positional argument: 'category_id' I have been trying to figure out how to fix the error Here is my views class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='category_created') name = models.CharField(max_length=500, db_index=True) slug = models.CharField(max_length=500, blank=True) images = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='product') category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=500, db_index=True) slug = models.CharField(max_length=500, blank=True) images = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) description … -
Django API timezone Dates in UTC
I'm developing an API in Django (note not DRF). I'm having this problem with datetime timezones. I'm storing everything in UTC, then in front-end I convert them to current timezone with moment.js. But then I have the problem with DateFields, for example: confirm_pickup_date = models.DateField(blank=True, null=True) Where the confirm_pickup_date can either be server current time, or custom date sent by the client from front-end as YYYY-MM-DD format. When i send the date by the client, i cant convert the Date to UTC -
Upgrading to django 1.9 AppRegistryNotReady: Apps aren't loaded yet
I'm migrating my project to 1.9 version, and when try to execute gives me that: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 324, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/init.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/prueba/djcode/spid/preventivos/init.py", line 6, in from django.contrib.auth.models import User File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 4, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/base_user.py", line 49, in class AbstractBaseUser(models.Model): File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 94, in new app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 239, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
POST request url does not match
first of all everything work fine on local but on the server every time that I request to server with a POST method, I get back 405 which says GET method not allowed, witch after my investigation it turned out that the first time that I send the POST request to server URL does not match(301), and then django try to send the GET request and in the result I get 405 which is correct because my view does not accept GET request I know maybe main urls url(r'^api/v1/account/', include('account.api.urls', namespace="apiAccount")), account urls url(r'^signup/$', views.APISignup, name="apiSignup"), and I send a request with POST method using Postman to: http://hostname.com/api/v1/account/signup/ I tryed with netbeans and android studio also but results was the same as before again every thing is okey on local and was key on server till our last deploy which I didnt change anything related to our API,I know maybe I am making foolish mistake but help me :) -
Django Rest Framework + Angular 2 - uploading multiple files
I'm using Django Rest Framework as my backend and Angular 2 for my frontend. I've got this page in Angular, where I create a form: createResourcesForm() { this.resourcesForm = this.formBuilder.group({ resources: this.formBuilder.array([ this.formBuilder.group({ title: ['', Validators.compose([Validators.required])], file: ['', Validators.compose([])], }) ]) }) } As you can see, the form consists of FormArray, where every element has two inputs: title and file - a text input and a file input respectively. On submitting the form I'm trying to send the data to Django but I get an error Missing filename. Request should include a Content-Disposition header with a filename parameter.. I could set it easily but I'm expecting to receive a list of {title, file}, so how to set multiple file names? Any other idea how I could do this? The error in Django Rest Framework comes from parse method in FileUploadParser. I'm not pasting any Python code here because it's a standard ListCreateAPIView, nothing special about it. Here is my serializer: class ResourceCreateSerializer2(serializers.Serializer): author_pk = serializers.IntegerField(required=False) author_first_name = serializers.CharField(max_length=50, required=False) author_last_name = serializers.CharField(max_length=50, required=False) resources = ResourceWithoutAuthorSerializer(many=True) class ResourceWithoutAuthorSerializer(serializers.ModelSerializer): instruments = InstrumentSerializer(many=True) class Meta: model = MusicResource fields = ['title', 'file', 'instruments'] Don't mind the other fields, they are being … -
"Prefecture.area" must be a "Area" instance
I got an error, ValueError: Cannot assign "<QuerySet [<Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, <Area: Area object>, '...(remaining elements truncated)...']>": "Prefecture.area" must be a "Area" instance. I wanna parse excel and put it to the model(City&Prefecture&Area&User) . I wrote fourrows_transpose = list(map(list, zip(*fourrows))) val3 = sheet3.cell_value(rowx=0, colx=9) user3 = User.objects.filter(corporation_id=val3).first() print(user3) if user3: area = Area.objects.filter(name="America") pref = Prefecture.objects.create(name="prefecture", area=user3.area) city = City.objects.create(name="city", prefecture=pref) price_u1000 = Price.upper1000.objects.get(city=city) price_500_1000 = Price.from500to1000.objects.get(city=city) price_u500 = Price.under500.objects.get(city=city) pref.name = "NY" pref.save() for i in range(len(fourrows_transpose)): city.name = fourrows_transpose[i][1] city.save() print(fourrows_transpose[i][1]) price_u1000.name = fourrows_transpose[i][2] price_u1000.save() print(fourrows_transpose[i][2]) price_500_1000.name = fourrows_transpose[i][3] price_500_1000.save() print(fourrows_transpose[i][3]) price_u500.name = fourrows_transpose[i][4] price_u500.save() print(fourrows_transpose[i][4]) I wanna put these data [['America', '', '', '', ''], ['', '', 'u1000', '500~1000', 'd500'], ['NY', 'City A', '×', '×', '×'], ['', 'City B', '×', '×', '×'], ['', 'City C', '×', '×', '×'], ['', 'City D', '×', '×', '×'], ['', 'City E', '×', '×', '×']] to models which … -
Use django model only as an app permissions container
I created an app 'control panel' that is used by my client instead of the django admin. Is it correct to create a model with no fields, used only as a permission container for the control panel? So I can permit/deny the access to the sections of the control panel -
I can't use my django model values in forms.py. I get : name 'user' is not defined
I'm trying to use a value from a django model, but I'm missing something in my code and I can't figure out what it is. I'm using django 1.11 Do I need the form class to inherit request? In case,how do I do that? from django import forms from .models import Profile from django.contrib.auth.models import User from django.shortcuts import render class form(forms.Form): department_string = ((user.profile.departnemt_1_number, 'Afd A',), ('2', 'Afd B',),) afdeling = forms.ChoiceField(widget=forms.RadioSelect, choices=department_string, initial='1') I get: Exception Value: name 'user' is not defined Any help is very appreciated! -
Django Rest Framework: @detail_route and @list_route with same name
I have a DRF ViewSet and would like to provide a detail and list routes with the same name: class MyViewSet(ViewSet): # ... @detail_route(['post']) def do_stuff(self, request, *args, **kwargs): pass @list_route(['post']) def do_stuff(self, request, *args, **kwargs): pass This obviously doesn't work, as the list_route will just overwrite the detail_route. Is there a simple way to provide both routes without manually messing up with the urls? -
Django NoReverseMatch, not a registered namespace
I have the following link in my project template: <li><a id="toggleLogin" href= "{% url 'login' %}" onclick="toggleLogin();" ><span>Login</span></a></li> <!-- login app --> the project url is: url(r'^login/',loginViews.user_login,name='login'), the application url is: url(r'^$',views.user_login,name='user_login'), and the application view is: def user_login(request): """User at login view """ # if request.method == 'POST': # First get the username and password supplied username = request.POST.get('username') password = request.POST.get('password') # Django's built-in authentication function: user = authenticate(username=username, password=password) # If we have a user if user: #Check it the account is active if user.is_active: # Log the user in. login(request,user) # Send the user back to some page. # In this case their homepage. return HttpResponseRedirect(reverse('index')) else: # If account is not active: return HttpResponse("Your account is not active.") else: print("Someone tried to login and failed.") print("They used username: {} and password: {}".format(username,password)) return HttpResponse("Invalid login details supplied.") else: #Nothing has been provided for username or password. return render(request, 'login.html', {}) But once the linked clicked, it returns the following django error: NoReverseMatch at /login/ 'login_app' is not a registered namespace should this namespace be registered in the project url file as well ? -
AttributeError: 'RelatedManager' object has no attribute 'remove'
Somewhere in my code it says publisher.publisherperson_set.remove(email__in=pp_remove_set) Upon executing this, I got AttributeError: 'RelatedManager' object has no attribute 'remove' And indeed: I looked at dir(publisher.publisherperson_set) and it had plenty of operations (including add), but not remove. Under which circumstances is this possible? -
Django : Can't import 'module'. Check that module AppConfig.name is correct
Might look like an already answered question, actually here you have the same problem (kind of) i had. My problem is, it's just a trick, one line, no explanation (and still it's different but the solution given works, and that's part of my problem). Here's my project structure, simplified: manage.py compfactu/---settings.py |--__init__.py |--core/--------__init__.py |-apps.py So here is how I added my app in INSTALLED_APPS: apps.py from django.apps import AppConfig class CoreConfig(AppConfig): name = 'core' settings.py INSTALLED_APPS = [ ... #compfactu modules 'compfactu.core.apps.CoreConfig', ] As I read the django 1.11 documentation, and I quote : New applications should avoid default_app_config. Instead they should require the dotted path to the appropriate AppConfig subclass to be configured explicitly in INSTALLED_APPS. Well nice, it's a new application so i should do that : but i'm getting an error. And it's not a problem of pythonpath, cause i just opened a python shell and I can do from compfactu.core.apps import CoreConfig with no problem (print the sys.path too, everything's fine). But I have this error, here's a full traceback: Traceback (most recent call last): File "/home/jbjaillet/Projets/venvcompfactu/lib/python3.5/site-packages/django/apps/config.py", line 147, in create app_module = import_module(app_name) File "/home/jbjaillet/Projets/venvcompfactu/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen … -
Django create dynamic model
I am building a web-page using python and Django and mysql and i have 5K tables that are identical in structure just the name is different Example: my_table_name_1 my_table_name_2 ... my_table_name_5000 How i can setup the model to have base template like "my_table_name_" and when i will call from the controller i want to pass the id and point to the right table FYI: my app in the projects is called 'polls' In my module.py i used ./manage.py inspectdb > models.py. but what happens whenever i add a new table in the db..i have to do all of this manual everytime. this is my polls/views.py class AboutDetail(DetailView): model = Crawledtables pk_url_kwarg = 'table_id' template_name = 'polls/details.html' def get_object(self): if 'table_id' not in self.kwargs: return Crawledtables.objects.get(id=1) else: return Crawledtables.objects.get(id=self.kwargs['table_id']) def home(request): return render(request, 'polls/base.html') def tables(request): tables = Crawledtables.objects.order_by('id') table_list = {'list_tables': tables} return render(request, 'polls/tables.html', context=table_list) class Details(ListView): model = Table1 template_name = 'polls/details.html' context_object_name = 'list' paginate_by = 15 queryset = Table1.objects.all() CrawledTable is just a table with all the names of tables that i crawled in that DB. polls/urls.py urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^tables/$', views.tables, name='tables'), url(r'^(?P<table_id>\d+)/$', views.AboutDetail.as_view(), name='id_details'), url(r'^(?P<table_id>\d+)/details$', views.Details, name='details'),] this is part of … -
Django admin inline inside another inline
I have 3 classes related to each other with FK. Course is grand parent, Step is parent, Substep is the kid. So each course has X steps and each step has X Substeps. When you add a new course I want to be able to add both steps and inside the steps I want to be able to add a Substep. Please see attached picture Now it won't show the Substep inline. Here is my models.py class Course(models.Model): created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=255) description = models.TextField() def __str__(self): return self.title class Step(models.Model): title = models.CharField(max_length=255) description = models.TextField() order = models.IntegerField(default=0) course = models.ForeignKey(Course) def __str__(self): return self.title class Substep(models.Model): title = models.CharField(max_length=255) description = models.TextField() order = models.IntegerField(default=0) step = models.ForeignKey(Step) def __str__(self): return self.title admin.py from . models import Course, Step, Substep class StepInLine(admin.StackedInline): model = Step class CourseAdmin(admin.ModelAdmin): inlines = [StepInLine,] class SubstepInLine(admin.StackedInline): model = Substep class StepAdmin(admin.ModelAdmin): inlines = [SubstepInLine,] admin.site.register(Course, CourseAdmin) admin.site.register(Step, StepAdmin) admin.site.register(Substep) -
Django - Time aggregates of DatetimeField across queryset
(using django 1.11.2, python 2.7.10, mysql 5.7.18) If we imagine a simple model: class Event(models.Model): happened_datetime = DateTimeField() value = IntegerField() What would be the most elegant (and quickest) way to run something similar to: res = Event.objects.all().aggregate( Avg('happened_datetime') ) But that would be able to extract the average time of day for all members of the queryset. Something like: res = Event.objects.all().aggregate( AvgTimeOfDay('happened_datetime') ) Would it be possible to do this on the db directly?, i.e., without running a long loop client-side for each queryset member? -
Date picker for django app using bootstrap4
This is the view and template for my Django app. The views are written using the django class based view. view.py class CreateDGThreePhase(CreateView): model = DGThreePhase fields = ['site','name','make','capacity','commissionDate',] def get_context_data(self, **kwargs): context = super(CreateDGThreePhase, self).get_context_data(**kwargs) context['list_objects'] = DGThreePhase.objects.all()[:10] return context class UpdateDGThreePhase(UpdateView): model = DGThreePhase fields = ['site','name','make','capacity','commissionDate',] class DeleteDGThreePhase(DeleteView): model = DGThreePhase template_name = 'sidebar_menu/delete_menu.html' def get_context_data(self, **kwargs): context = super(DeleteDGThreePhase, self).get_context_data(**kwargs) context['model_name'] = context['object'].__class__.__name__ return context template-> dgthreephase_form.html {% extends 'common/base.html' %} {% load crispy_forms_tags %} {%block body %} <div class="col-md-12"> <div class="row"> <div class="col-md-8"> <h4>DG Three Phase Management</h4> <div class="tro-form"> <form method="POST" ng-non-bindable> {% csrf_token %} {{form | crispy}} <input type="submit" value="Save" class="btn btn-success" /> {% if request.resolver_match.url_name == 'dgthree_phase_update' %} Or <a href="{% url 'sites:dgthree_phase_create' %}">Cancel</a> <a href="{% url 'sites:dgthree_phase_delete' pk=object.id %}" class="btn btn-danger pull-right">Delete</a> {% endif %} </form> </div> </div> <div class="col-md-4"> <h4>DG Three Phase List</h4> <div class="tro-form"> <input type="text" class="form-class" style="padding: 4px 4px 4px 10px;" placeholder="Search..." id="id_search_menu"/> <div class="list-group" style="padding-top: 5px" id="menu_list_id"> {% for list in list_objects %} <a href="{% url 'sites:dgthree_phase_update' pk=list.id %}" class="list-group-item list-group-item-action"> {{list.name}} </a> {% endfor %} </div> </div> </div> </div> </div> {% endblock%} How can I add a date picker for the commissionDate Field using bootstrap4? CommisionDate is … -
Trying to make Django slider but not sliding images only showing first image
I am trying to adapt to my Django project image slider. But images are not sliding. Here original HTML code: <section id="slider" class="fullheight nomargin" data-background-delay="3500" data-background-fade="1000" data-background=" imagefile1.jpg ,imagefile2.jpg ,imagefile3.jpg "> <!-- Backstretch Navigation --> <a class="bs-next" href="#"></a> <a class="bs-prev" href="#"></a> <div class="display-table"> <div class="display-table-cell vertical-align-middle"> <div class="container text-center"> <div class="rounded-logo wow fadeIn" data-wow-delay="0.4s"> <img src="demo_files/images/packs/hotel/logo.png" alt=""> </div> <h1 class="weight-300 margin-top-30 margin-bottom-0 wow fadeIn" data-wow-delay="0.6s">SMARTY HOTELS</h1> </div> </div> </div> <span class="raster overlay dark-3 z-index-0"><!-- dark|light overlay [0 to 9 opacity] --></span> </section> ` And Django template <section id="slider" class="fullheight nomargin" {% for carousel_item in carousel_items.all %} {% if carousel_item.image %} data-background-delay="3500" data-background-fade="1000" {% if carousel_item.embed_url %} {% else %} {% image carousel_item.image width-1000 as carouselimagedata %} data-background="{{ carouselimagedata.url }}"style="width: 100%; min-height: {{ carouselimagedata.height }}px;" alt="{{ carouselimagedata.alt }}"{% if not forloop.last %},{% endif %} {% endif %} {% endif %} > <canvas id="canvas-particle" class="opacity-8" data-rgb="13,144,179"><!-- CANVAS PARTICLES --></canvas> <!-- Backstretch Navigation --> {% if carousel_items|length > 1 %} <a class="bs-next" href="#"></a> <a class="bs-prev" href="#"></a> {% endif %} <div class="display-table"> <div class="display-table-cell vertical-align-middle"> <div class="container text-center"> <div class="rounded-logo wow fadeIn" data-wow-delay="0.4s"> <img src="{% static 'images/logo.png' %}" alt=""> </div> {% if carousel_item.caption %} <h1 class="weight-300 margin-top-30 margin-bottom-0 wow fadeIn" data-wow-delay="0.6s">{{ carousel_item.caption }}</h1> {% … -
app.models.MultipleObjectsReturned: get() returned more than one User -- it returned 17
I got an error,app.models.MultipleObjectsReturned: get() returned more than one User -- it returned 17! . I wanna parse excel and put it to the model(City&Prefecture&Area&User) . I wrote fourrows_transpose = list(map(list, zip(*fourrows))) val3 = sheet3.cell_value(rowx=0, colx=9) user3 = User.objects.get(corporation_id=val3) print(user3) if user3: area = Area.objects.filter(name="America") pref = Prefecture.objects.create(name="prefecture", area=user3.area) city = City.objects.create(name="city", prefecture=pref) price_u1000 = Price.upper1000.objects.get(city=city) price_500_1000 = Price.from500to1000.objects.get(city=city) price_u500 = Price.under500.objects.get(city=city) pref.name = "NY" pref.save() for i in range(len(fourrows_transpose)): city.name = fourrows_transpose[i][1] city.save() print(fourrows_transpose[i][1]) price_u1000.name = fourrows_transpose[i][2] price_u1000.save() print(fourrows_transpose[i][2]) price_500_1000.name = fourrows_transpose[i][3] price_500_1000.save() print(fourrows_transpose[i][3]) price_u500.name = fourrows_transpose[i][4] price_u500.save() print(fourrows_transpose[i][4]) I wanna put these data [['America', '', '', '', ''], ['', '', 'u1000', '500~1000', 'd500'], ['NY', 'City A', '×', '×', '×'], ['', 'City B', '×', '×', '×'], ['', 'City C', '×', '×', '×'], ['', 'City D', '×', '×', '×'], ['', 'City E', '×', '×', '×']] to models which is like 'America' to Prefecture's area and City A to City's name and × to Price's name . How can I fix this?What should I write it? -
How to add existing django project onto git hub
I have created Django python web app .How to add it to github am new to both of these and have searched web for somedays without any luck. -
Unit test to assertRedirects of login?
I have custom login page for admin in my Django project. I am trying to write unit-test but it raise error. After successful login Django redirect user to other page (dashboard page). In my unit test dont work assertRedirects. How to fix this problem? print reverse('administration:dashboard') return me /administration/ but I have strange error. Can someone say whats wrong I did? tests.py: class AdministrationViewTestCase(TestCase): def setUp(self): self.client = Client() def test_administration_login(self): response = self.client.get( reverse('administration:administration_login'), follow=True ) self.assertEquals(response.status_code, 200) title = "Login" self.assertTrue(title in response.content) user = User.objects.create( username='user', password=make_password('password') ) self.assertTrue(user) logged_in = self.client.login(username='user', password="password") self.assertTrue(logged_in) response = self.client.post( reverse('administration:administration_login') ) self.assertEqual(response.status_code, 302) self.assertRedirects( response, expected_url=reverse('administration:dashboard'), status_code=302, target_status_code=200 ) ERROR: Traceback (most recent call last): File "/home/nurzhan/CA/administration/tests.py", line 41, in test_administration_login target_status_code=200 File "/srv/envs/py27/lib/python2.7/site-packages/django/test/testcases.py", line 324, in assertRedirects % (path, redirect_response.status_code, target_status_code) AssertionError: Couldn't retrieve redirection page '/accounts/profile/': response code was 404 (expected 200) urls.py of app: urlpatterns = [ # Administration Dashboard url(r'^$', login_required( login_url=reverse_lazy('administration:administration_login')) (DashboardView.as_view()), name='dashboard'), # Administration Login url(r'^login/$', authentication_views.login, { 'template_name': 'administration/login.html', 'authentication_form': AdministrationAuthenticationForm, 'extra_context': { 'next': reverse_lazy('administration:dashboard') }, 'redirect_authenticated_user': True }, name='administration_login'), ] urls.py of project: urlpatterns = [ # Administration Page url(r'^administration/', include('administration.urls', namespace='administration')), ] -
name 'category_id' is not defined
I am trying to get the id of the category but this error keeps up poping. Here is my models class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='category_created') name = models.CharField(max_length=500, db_index=True) slug = models.CharField(max_length=500, blank=True) images = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='product') category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=500, db_index=True) slug = models.CharField(max_length=500, blank=True) images = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField(blank=True) available = models.CharField(max_length=25) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(Product, self).save(*args, **kwargs) This is my views where by errors is occuring from and don't know how to fix the views and i am sure the problem is from my views @login_required def product(request): if request.method == 'POST': category = Category.objects.get(pk = category_id) product_form = ProductForm(data=request.POST, files=request.FILES) if product_form.is_valid(): new_item = product_form.save(commit=False) new_item.category = category new_item.save() messages.success(request, 'Product created') else: messages.error(request, 'Product Failed to be created') else: product_form = ProductForm() return render(request, 'shop/product/product_create.html', {'product_form':product_form}) Here is my url for the view urlpatterns = [ url(r'^category-create/$', … -
How to get collectstatic to collect the static files of an external App
I'm working on a project that requires an external fileupload package, which is a separate project. 'collectstatic' does not include the static files of that external package. Do I need to change the external package or can I use the settings.py of my project to include the static files? It works if I do: STATICFILES_DIRS = ( str(APPS_DIR.path('my_app/static')), str(APPS_DIR.path('../other_app/fileupload/static')) ) But this will not work on the deployment server.