Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GET method has taken by Django
I am a beginner in Django and I am creating Django forms for getting input and processing. I created my app called 'artists' and I have coded the files as follows. This is my urls.py in server folder """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^artists/', include('artists.urls')), ] These are my files in 'artists' app -> urls.py <- from django.conf.urls import url from . import views urlpatterns = [ url(r'^artists/', views.artistcreate, name="artistcreate")] -> views.py <- from django.shortcuts import render, render_to_response from django.template import RequestContext from datetime import datetime from artists.models import * def artistcreate(request): if request.method=="GET": form=ArtistForm() return render(request,'artists/create.html',{'form':form}) elif request.method=="POST": form=ArtistForm(request.POST) form.save() return HttpResponseRedirect('/artists') -> models.py <- from django.db import models from django.forms import ModelForm … -
How to upload images from django-tinyMCE WYSIWYG editor in the admin panel
I am not able to upload images in Django blog app that I am working on. I require the images to uploaded from the admin panel in the tinyMCE WYSIWYG editor This is my settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'blog', 'contact', 'tinymce', 'filebrowser', 'grappelli', ] tinyMCE settings TINYMCE_DEFAULT_CONFIG = { 'plugins': "table,spellchecker,paste,searchreplace", 'theme': "advanced", 'mode' : 'textareas', 'theme' : 'advanced', 'plugins' : 'safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager,filemanager', 'height': "500px", 'width': "1200px", 'theme_advanced_buttons1' : 'save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect', 'theme_advanced_buttons2' : 'cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor', 'theme_advanced_buttons3' : 'tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen', 'theme_advanced_buttons4' : 'insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage', 'theme_advanced_toolbar_location' : 'top', 'theme_advanced_toolbar_align' : 'left', 'theme_advanced_statusbar_location' : 'bottom', 'theme_advanced_resizing' : True, } TINYMCE_SPELLCHECKER = True TINYMCE_COMPRESSOR = True TINYMCE_FILEBROWSER = True URL_FILEBROWSER_MEDIA = 'filebrowser/media/' This is my models.py class Entry(models.Model): body = tinymce_models.HTMLField() image=FileBrowseField("Image", max_length=200, blank=True, null=True) I don't get any errors but I am not able to upload images inside my editor here is the SNAP SHOT -
Parse request file and body from post request
I am trying to send an image via post together with some other fields, but in my view I can only get access to my image and not the other fields. test def testCreateEvent(self): """ Tests to create a event. :return: """ with open("files/test_images/test1.jpg", 'rb') as image: content = { "name": "Event", "start": self.start_date.strftime('%Y-%m-%d %H:%M:%S'), "end": self.end_date.strftime('%Y-%m-%d %H:%M:%S'), "location": "C2", "last_register": self.last_reg.strftime('%Y-%m-%d %H:%M:%S'), "open_register": self.open_reg.strftime('%Y-%m-%d %H:%M:%S'), "max_participants": 100, "file": image } response = self.c.post("/event/1/", content, format='multipart', **{"HTTP_AUTHORIZATION": "Bearer " + self.token}) self.assertEqual(response.status_code, 200) view @require_POST @verify_token def create_event(request, host_id, liu_id): url = request.FILES['file'] print("URL",url) event_info = request.body print("EVENT INFO", event_info['name']) host = HostAdmin.objects.filter(student__liu_id=liu_id, host__id=host_id) if len(host) != 1: response = HttpResponse("Unauthorized") response.status_code = 401 return response event = Event.objects.create(name=event_info['name'], start=event_info['start'], end=event_info['end'], last_register=event_info['last_register'], open_register=event_info['open_register'], location=event_info['location'], host_id=host_id, max_participants=event_info['max_participants']) ... I can get my file url, but on the line where "print("EVENT INFO", event_info['name'])" I get the following error: raise RawPostDataException("You cannot access body after reading from request's data stream") django.http.request.RawPostDataException: You cannot access body after reading from request's data stream -
Django doesn't respond on some requests after deployment on server
I have a little bit weirdo behavior, of my Django app, after deployment on server with gunicorn. First, I add script to upstart, using runit tool (linux, of course). And saw that my server respond on request as it wants. Maybe it respond on request, maybe not. I was shocked, because the same configuration on my local machine works the same. So, I decided to remove script from upstart, and try to run it as on local machine, with the same script, that I removed from runit upstart. Result is better, it respond on 95 of ajax calls, but one is still does not works. Screen from chrome network monitoring. 10 seconds, takes SIMPLE request for stop/ url. I never saw, that server respond to client on start/ url, when app deployed on server. There are screens from my local machine, from Chrome network monitoring. I run apps on google compute engine, so I thought that server have not enough performance. But it's wrong. Changes of machine type have no influence. Then, I decided to take a look to logs and code. Before response I wrote these lines of code: log.info('Start activity for {}'.format(username)) return HttpResponse("started") And I can see … -
Django forms doesn't save changes to db
Guys, created profile form, but it doesn't save changes to db. Would be very thankful for your advice snippets: views.py def edit_profile(request): if request.method == "POST": form = UserEditProfile(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('profile') else: form = UserEditProfile(instance=request.user) args = {'form': form} return render(request, 'edit.html', args) forms.py class UserEditProfile(UserChangeForm): class Meta: model = Profile fields = ( 'first_name', 'last_name', 'date_of_birth', 'biography', 'contacts', 'password' ) urls.py urlpatterns = [ url(r'^profile/$', views.ProfileView.as_view(), name='profile'), url(r'^profile/edit/$', views.edit_profile, name='edit'), ] models.py class Profile(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField() biography = models.TextField() contacts = models.CharField(max_length=200) edit.html <body> <div class="container"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> <br> </div> </body> It doesn't show any mistakes, but after submit it has to save changes to db, but it doesn't. How -
Django Celery Result : Django-DB ttributeError: 'DisabledBackend'
I'm currently testing Django Celery Results using Django DB as backend. I've followed the documentation here: http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#django-celery-results-using-the-django-orm-cache-as-a-result-backend When my Django view calls the celery task, it gets properly added in the Django DB and the task gets executed by Celery worker. I can also fetch the task ID with below code: def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data res = mailer.delay( cd['subject'], cd['message'], cd.get('email', 'noreply@gmail.com'), ['seb.pouplin@gmail.com']) cel_taskid = res.task_id result = AsyncResult(cel_taskid) print(result.state) return HttpResponse(cel_taskid) However, whenever I try to fetch task status, state or ready() flag, I'm getting following exception: AttributeError: 'DisabledBackend' object has no attribute '_get_task_meta_for' Is there any limitation using Django-DB to get the task details or any other way to retrieve them ? Thanks in advance -
CSRF token gets passed in the header when performing POST
I'm setting up VueJS SPA on top of Django. I have Graphene endpoint running on /api and queries in graphiql run fine. I have set up frontend and I'm using Apollo Client to query server. There goes my setup: const CSRFtoken = Cookies.get('csrftoken') const networkInterface = createNetworkInterface({ uri: '/api', transportBatching: true }) networkInterface.use([{ applyMiddleware (req, next) { if (!req.options.headers) { req.options.headers = {} // Create the header object if needed. } req.options.headers['X-CSRFToken'] = CSRFtoken console.log('applied middleware') next() } }]) const apolloClient = new ApolloClient({ networkInterface, connectToDevTools: true }) Vue.use(VueApollo) const apolloProvider = new VueApollo({ defaultClient: apolloClient }) new Vue({ el: '#app', apolloProvider, render: h => h(App) }); My POST requests have the 'X-CSRFToken' header with value provided by Cookies. Screenshot below: I have searched through the web but can't find anything related. Thanks in advance! -
how to fix RuntimeWarning: DateTimeField received a naive > datetime while time zone support is active?
full traceback C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\fields__init__.py:1451: RuntimeWarning: DateTimeField UserProfile.key_expires received a naive datetime (2017-07-04 14:18:43) while time zone support is active. RuntimeWarning) this is my userprofile model class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) slug = models.SlugField(unique=False, default=None, blank=True) activation_key = models.CharField(max_length=90, default=None, blank=True) key_expires = models.DateTimeField(default=None) this is view profile = UserProfile.objects.create( user=user, slug=username, key_expires=datetime.datetime.strftime(timezone.now() + datetime.timedelta(days=2), "%Y-%m-%d %H:%M:%S"), activation_key=get_secret_key ) -
How to add Angular 4 to Docker with Django project?
I would like to add Angular 4 project to Docker with Django project? My structure of files look in this way: DockerContainer: Backend Dockerfile Frontend docker-compose.yml requirements.txt I would like to create Angular 4 project in Frontend directory. I can do this using ng new my-app but what should I do next? This is my docker-compose.yml: version: '3' services: db: image: postgres django: build: . command: python3 Backend/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Dockerfile: FROM python:3.6.1 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ -
Correctly loading Keras model in Django that supports multi-tenancy
I am try to write a REST api in django that uses a Keras model to return a prediction. However the load_model() function takes some time to load the model and I don't want my users to have to wait so long (each time the model is initialized). What would be the correct way to initialize the model so that is is loaded once and the predictions are done using that same model? On a side note one method that I thought cold be possible was to initialize the model in settings.py as below : settings.py json_file=open("model.json","r") loaded_json=json_file.read() json_file.close() model=model_from_json(loaded_json) model.load_weights("model.h5") MODEL=model And then in my views.py I use this variable MODEL as : views.py from django.conf import settings model=settings.MODEL def index(): print "Predicting" res=model.predict(numpy.stack([test_img])) print res This works great if only one user is active at a time ( model is initialized once and all subsequent predictions are done using that model). However if multiple users are active at a time then it works good for the call that came first but the latter call gives the error 'NoneType' object has no attribute 'shape' Apply node that caused the error: ConvOp{('imshp', (31, 31, 32)),('kshp', (3, 3)),('nkern', 64),('bsize', None),('dx', 1),('dy', … -
URL passes parameter in my Django project
I am just a beginner of Django, these days I followed a mooc to learn Django, I wanted to set up my first website, but something went wrong and I can not figure out. I wanted to write a regex with parameter 'cate' in URLS.py to match the video function in my view.py, judging whether 'cate' eequals 'editors', if yes it will bring back data with attribute "editors_choice". However, I found no it never changes, so I printed 'cate' in view.py and found it always None and I still don't know why. Following is my code: def video(request, cate=None): print(cate) context = {} = if cate is None: video_list = Video.objects.all() if cate == 'editors': video_list = Video.objects.filter(editors_choices=True) else: video_list = Video.objects.all() page_robot = Paginator(video_list, 16) page_num = request.GET.get('page') try: video_list = page_robot.page(page_num) except EmptyPage: video_list = page_robot.page(page_robot.num_pages) # raise HTTP404("Empty") except PageNotAnInteger: video_list = page_robot.page(1) context['video_list'] = video_list return render(request, 'ten_movie.html', context) -
Validation error with django formsets (blank fields not accepted)
I have two models (Workout and ExerciseSet) that are connected in a One to Many relationship. I'm trying to use a CreateView to build a form that allows me to create a workout and exercise set(s) at the same time. The thing is when I only have one exercise set field (extra=1 in the inlineformset_factory), it works - but when I want to set extra to a larger number like 3, it will only work if all the workouts are set up. Otherwise it throws a null value in column "repetitions" violates not-null constraint error. I'm thinking of overwriting the clean method in the inlineformset class to solve this, but when I call super.clean(), it keeps returning None. Just wondering if anyone could help. models.py class Workout(models.Model): profile = models.ForeignKey( 'Profile', on_delete=models.CASCADE, blank=False ) class ExerciseSet(models.Model): EXERCISE_TYPE_CHOICES = ( ('pushup', 'Push Up'), ('situp', 'Sit-up') ) workout = models.ForeignKey( 'Workout', on_delete=models.CASCADE, related_name='exercise_sets' ) repetitions = models.PositiveIntegerField() exercise_type = models.CharField(max_length=100, choices=EXERCISE_TYPE_CHOICES) forms.py class WorkoutForm(ModelForm): class Meta: model = Workout exclude = () class ExerciseSetForm(ModelForm): class Meta: model = ExerciseSet exclude = () class CustomExerciseSetInlineFormSet(BaseInlineFormSet): def clean(self): cleaned_data = super().clean() print('custom') print(cleaned_data) ExerciseSetFormSet = inlineformset_factory(Workout, ExerciseSet, form=ExerciseSetForm, formset=CustomExerciseSetInlineFormSet, extra=3) views.py class WorkoutCreate(CreateView): model … -
Django Rest Framework: Register User model to Course model
I have a Django REST API that has a User and Course model defined as: class User(AbstractBaseUser): id = models.UUIDField(primary_key = True, default=uuid.uuid4) username = models.CharField(blank=False, max_length=32, unique=True) notes = models.ForeignKey('notes.Note', null=True, related_name='notes') courses = models.ManyToManyField(Course, related_name='courses') class Course(models.Model): course_name = models.CharFIeld(max_length=64) course_tutor = models.ForeignKey('authentication.User', related_name='tutor', blank=True) course_students = models.ManyToManyField('authentication.User', editable=True, related_name='students') My serializers are defined like this class UserSerializer(serializers.ModelSerializer): notes = serializers.SerializerMethodField('get_notes_for_user') courses = serializers.SerializerMethodField('get_courses_for_student') def get_courses_for_student(self, obj): # What do I do here?? def get_notes_for_user(self, obj): queryset = Note.objects.all().filter(note_owner=obj) return queryset.values() class Meta: model = User fields = ('id', 'username', 'notes', 'courses') class CourseSerializer(serializers.HyperlinkedModelSerializer): course_students = serializers.HyperlinkedRelatedField(view_name='user-detail', lookup_field='pk', many=True, read_only=True) class Meta: model = Course fields = ('course_name', 'course_tutor', 'course_students', ) My question is: How do I correctly (and RESTful) register users to courses? I have thought of an intermediate model such as Subscriptions but I do not know the correct approach. The endgoal is to have an User/Course/Activity API that allows certain Users to "subscribe" (Hence the intermediate Subscription model) to a certain course/activity. I'm troubling myself over how to implement this and would appriciate additional insights. If I have failed to provide enough details to resolve this please do tell. I will gladly supply any additional … -
Fail with django app on azure
I'm trying to develop and deploy django app on azure web apps. While following the tutorial on azure website, after cloning the basic project to my local machine (using git) and creating the virtual environment, I'm trying to run the createsuperuser commend, and getting this error: C:\Users\tutzy\Desktop\newtest\amir1>env\scripts\python manage.py createsuperuser Traceback (most recent call last): File "manage.py", line 17, in <module> execute_from_command_line(sys.argv) File "C:\Users\tutzy\Desktop\newtest\amir1\env\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line utility.execute() File "C:\Users\tutzy\Desktop\newtest\amir1\env\lib\site-packages\django\core\management\__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\tutzy\Desktop\newtest\amir1\env\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\tutzy\Desktop\newtest\amir1\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 52, in execute return super(Command, self).execute(*args, **options) File "C:\Users\tutzy\Desktop\newtest\amir1\env\lib\site-packages\django\core\management\base.py", line 413, in execute translation.activate(saved_locale) File "C:\Users\tutzy\Desktop\newtest\amir1\env\lib\site-packages\django\utils\translation\__init__.py", line 154, in activate return _trans.activate(language) File "C:\Users\tutzy\Desktop\newtest\amir1\env\lib\site-packages\django\utils\translation\trans_real.py", line 216, in activate _active.value = translation(language) File "C:\Users\tutzy\Desktop\newtest\amir1\env\lib\site-packages\django\utils\translation\trans_real.py", line 205, in translation _translations[language] = DjangoTranslation(language) File "C:\Users\tutzy\Desktop\newtest\amir1\env\lib\site-packages\django\utils\translation\trans_real.py", line 118, in __init__ raise IOError("No translation files found for default language %s." % settings.LANGUAGE_CODE) IOError: No translation files found for default language en-us. I'm try to find the sulotion for hours, so I'll be thrild if someone could help me. -
How to get JSON Object from user through Django form textarea input field
I'm new to Django, I want to get a JSON object from the user through textarea input field then I need to parse this object to get all key-values.I don't have any idea how to do it, can someone help me, please! Thanks in advance! -
DRF hyperlinked list view lookup_field error
When changing the lookup_field, an error occurs. What I don't understand is why the error occurs when accessing the list view, but not when accessing the detail view. Any ideas, why this happens? http://localhost:8000/shops/ ImproperlyConfigured at /shops/ Could not resolve URL for hyperlinked relationship using view name "shops-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. View: class ShopViewSet(viewsets.ModelViewSet): queryset = Shop.objects.all() serializer_class = ShopSerializer lookup_field = 'slug' Serializers: class ShopMaintainerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ShopMaintainer fields = ('url', 'id', 'role', 'user',) class ShopSerializer(serializers.HyperlinkedModelSerializer): maintainers = ShopMaintainerSerializer(many=True, read_only=True) class Meta: model = Shop fields = ('url', 'name', 'slug', 'profile_image', 'cover_image',\ 'state', 'maintainers', 'created_at',) read_only_fields = ('created_at',) extra_kwargs = { 'url': {'lookup_field': 'slug'}, } Router setup: router = routers.SimpleRouter() router.register(r'shop', ShopViewSet) urlpatterns = [ url(r'^', include(router.urls)), ] -
Remove duplication in python django_tables2
I'm using django_tables2, and have ended up with the following two tables which are almost identical: class UserMapsetTable(Table): edit = ButtonColumn('Edit', 'mapsets_users_edit') mappings = ButtonColumn('Mappings', 'mapsets_users_mappings') class Meta: model = UserMappingRuleSet fields = ( 'name', 'notes' ) attrs = responsive_table_attrs() class ReadingMapsetTable(Table): edit = ButtonColumn('Edit', 'mapsets_readings_edit') mappings = ButtonColumn('Mappings', 'mapsets_readings_mappings') class Meta: model = ReadingMappingRuleSet fields = ( 'name', 'notes' ) attrs = responsive_table_attrs() How do I remove/reduce the duplication? -
Which is better to work on Python with Django or Ruby on Rails? Based on stability and functionality [on hold]
I am designing a website based on transaction and Artificial intelligence. So I want to ask which technology ,either python with django or ruby on rails, will be more helpful based on stability and functionality? -
DJango Api using SOAP web service
I wants to give some other websites apis using SOAP (wsdl) . I Want to use DJango Framework. what's best way to handle this? -
Searching for the most optimal solution with Django, Docker, virtualenv and structure of files
I wonder if I should use Docker with Django project and virtualenv or just with Docker? I have also problem with structure of my files. Let's assume that I would like to have frontend in my Project. It seems to me that all files should be in Docker container. Can anyone show me how the most optimal solution should look like? For instance in main Docker directory should I have Backend and Frontend directories? -
Django 1.11 ManifestStaticFilesStorage - all hashed static files return 404
I have these settings in settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' I've run collectstatic and there are files in /static/app/js directory: jquery-3.2.1.min.c9f5aeeca3ad.js jquery-3.2.1.min.js I'm just using Django's runserver to test this at the moment. If I run with DEBUG = True, everything works, as the JS is fetched from /static/app/js/jquery-3.2.1.min.js If I run with DEBUG = False, all static files fail with 404. The JS URL is now /static/app/js/jquery-3.2.1.min.c9f5aeeca3ad.js The URL looks correct, the files exist, what could be causing this to fail? My view includes: {% load static %} <script src="{% static 'app/js/jquery-3.2.1.min.js' %}"></script> Am I missing a setting? (using Django 1.11, Python 3.6) -
How to allow a user to view data that is added only by him Django Admin
I have a Django application, where the user with restricted access registers a new post in Django admin. This user can only see in the table to register, update and delete the posts inserted by him, and can not view the posts entered by another user, all within Admin Django, unless it has super user status. I've tried, create "def queryset" in my "NoticiaAdmin (admin.ModelAdmin)" class, and unfortunately I do not know what I'm doing wrong, I can not solve this problem. Here is my queryset function... def queryset(self, request): if request.user.is_superuser: qs = self.model._default_manager.get_query_set() else: qs = self.model._default_manager.get_query_set().filter(user=request.user) ordering = self.ordering or () if ordering: qs = qs.order_by(*ordering) return qs I hope I have clarified my doubts about the problem and I will be very grateful to anyone who can help me. -
Django endless pagination on scroll
i want to update my content while the user scrolling to end of the page i visited the documentation ( twitter pagination, ... ) but it didn't work for me so can i get some help ** i'am using wagtail ( django) this is my model.py #import .... class BlogIndexPage(Page): intro = RichTextField(blank=True) def get_context(self, request): # Update context to include only published posts, ordered by reverse-chron context = super(BlogIndexPage, self).get_context(request) blogpages = self.get_children().live().order_by('-first_published_at') context['blogpages'] = blogpages return context class BlogPage(Page): #..... indexpage.html {% extends "base.html" %} {% load wagtailcore_tags %} {% load wagtailcore_tags wagtailimages_tags %} {% block body_class %}blog index page{% endblock %} {% block content %} <center><h1>{{ page.title }}</h1></center> <div class="container"> <div class="row"> {% for post in blogpages %} <div class="col-mdl"> {% with post=post.specific %} <h4><a href="{% pageurl post %}">{{ post.title }}</a></h4> {% with post.main_image as main_image %} {% if main_image %}{% image main_image fill-351x281 %}{% endif %} {% endwith %} {% endwith %} </div> {% endfor %} </div> </div> {% endblock %} ** i don't have views -
Django DetailView for related objects
I am making an inventory app that have products and invoices .. I want to view the invoice and all the products related to it example of the out put I want: Invoice ID = 1 "all info about invoice" Products = Car, T-shirt, ...etc "with all details of each product" here is the models: class Products(models.Model): barcode = models.CharField(max_length=200) product_code = models.CharField(max_length=100) name = models.CharField(max_length=100) description = models.TextField() category = models.ForeignKey(Category) quantity_in_stock = models.IntegerField() quantity_on_hold = models.IntegerField() expire_date = models.DateField() unit_price = models.DecimalField(max_digits=9, decimal_places=2) vendor = models.CharField(max_length=100) manufacturer = models.CharField(max_length=100) discount = models.DecimalField(max_digits=9, decimal_places=2) def __str__(self): return self.name class Invoices(models.Model): invoice_number = models.CharField(max_length=100, unique=True) customer = models.ForeignKey(Customer) agent = models.ForeignKey(Agent) date = models.DateTimeField(auto_now_add=True) invoice_due_date = models.DateTimeField() amount = models.DecimalField(max_digits=9, decimal_places=2) discount = models.IntegerField() status = models.CharField(max_length=100, choices=Status) type = models.CharField(max_length=100, choices=Type) remaining = models.DecimalField(max_digits=9, decimal_places=2) def __str__(self): return self.invoice_number class InvoiceDetail(models.Model): invoice = models.ForeignKey(Invoices, related_name="invoice") product = models.ForeignKey(Products, related_name="product") product_description = models.TextField() product_price = models.DecimalField(max_digits=9, decimal_places=2) quantity_sold = models.DecimalField(max_digits=9, decimal_places=3) I have a template to list all invoices it's view: class InvoicesView(View): invoices = Invoices.objects.order_by('date') context = {'invoices': invoices} def get(self, request): return render(request, 'inventory/invoices.html', self.context) and i do the the detail page using this link: <a href="/sales/invoice/{{invoice.invoice_id}}"> urls: … -
Redirect and a different html page being called, but same url
I'm working through various Django tutorials in order to get an LDAP Backend up and running. I have a simple login page using a user's credentials, and an extra field to insert a user to be searched for. When hitting the submit button on my page, I get redirected to the correct html, but the url remains the same. I'm not sure that this could pose any problems, but if not, does it really matter if a different page has the same url? How should I be calling the redirected page? urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', ldap_authentication, name='index'), url(r'^logout/$', logout_view, name='logout'), url(r'^search_page/$', ldap_authentication, name="search_page") ] views.py def ldap_authentication(request): if request.POST: username = request.POST['username'] password = request.POST['password'] searchFilter = request.POST['searchUser'] domain_and_login = '{}\\{}'.format(DOMAIN_NAME, username) ''' Connection to LDAP... ''' split_dn = [domain_and_login, "ou=Konzern", "dc=abcdef", "dc=de"] return render(request, 'search_page.html', {'dn':split_dn}) return render(request, 'login.html') If I do a redirect, then I understand that Django looks this up in the urls.py, however the search_page.html doesn't have any view in the views.py.