Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF accepts int value although it serialzes to a charfield
Hello good people good Django, I was exploring DRF and made a simple CRUD API and everything was smooth nothing special here. But when trying to test how DRF will handle the different cases of missing and wrong values in a POST request I got something was actually very weird. First, here is an example of a valid body of POST request data: { "title": "It doesn't matter", "description": "A short one because life is fast", "body": "Test test test test" } All is a string as you can see. So, I replaced a string value with an int value instead ( like 96 not "96" for sure ) and surprisingly the POST request was successful, the serializer converted the int value to string and inserts it, it didn't raise an error or anything, so is there an explanation for this? -
How to create search view for movie database that can find movie based on title, and tittle + year in search
I am looking to create a search class that can find the movie when the title has been input into my form, but also want it to find said movie when the title and year is input into form as well. This is the view.py I have atm which will find movie based on title, but once I add the year on the end, it will not find it. ''' from django.shortcuts import render from django.views.generic import TemplateView, ListView, DetailView from .models import Movie from django.db.models import Q class HomePageView(TemplateView): template_name = 'movies/front_page.html' class SearchResultsView(ListView): model = Movie template_name = 'movies/search_results.html' context_object_name = 'search_all_movies' def get_queryset(self): query = self.request.GET.get('q') return Movie.objects.filter(Q(title__icontains=query) ''' -
"How to integrate File upload field in wagtail with other Wagtail_Fields?"
I want code of how to upload files in wagtail user forms and when submit form I get form record on wagtail admin panel. I want this form in frontend and when submit data i got it on wagtail adminpanel like that. Same as this code but i want file upload field in Form Fields here. from modelcluster.fields import ParentalKey from wagtail.admin.edit_handlers import ( FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel ) from wagtail.core.fields import RichTextField from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField class FormField(AbstractFormField): page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='custom_form_fields') class FormPage(AbstractEmailForm): intro = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('intro', classname="full"), InlinePanel('custom_form_fields', label="Form fields"), FieldPanel('thank_you_text', classname="full"), MultiFieldPanel([ FieldRowPanel([ FieldPanel('from_address', classname="col6"), FieldPanel('to_address', classname="col6"), ]), FieldPanel('subject'), ], "Email"), ] def get_form_fields(self): return self.custom_form_fields.all() -
Django Admin how to add filter menu like basic UserModel:
This is how looks template of Django Admin Model: This is model which I created: class ProfileUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.URLField() is_qualified = models.BooleanField(default=False) How can I create same filter menu ? for is_qualified ? -
Passing a model object (with many fields) from a viewfunction to another using redirect and without saving it
I am quite new in this field... so be gentle :) The problem can be stated as follow: View 1: a form based on a model of 14 fields is presented. The user fills it and presses the post button. (important: not saving the model instance in the DB) View 2: A confirmation page appears containing a summary of what he entered. He is asked then to - cancel (don't bother to erase anything in the database) - edit (is not yet saved but the information can be changed) - confirm it (now it's time to save it in the database). And should be accessible only one time, if not completed... it disappears (avoid to create an enormous number of instance in the DB) At the moment everything is static as it save in the DB from the start and stay there, so if someone jsut leave, it will remain in the DB for nothing I looked for some solutions but always cracked below errors. The first one is to directly pass the model instance (Mycard) which landed to > 'str' object has no attribute '_meta' So I looked to pass the information through the URL but it looks like … -
Search engine url, removal get data from empty forms fields. Django, queryset
I create a simple search engine in django. I would like to get a nice URL from here, even if a field will not be selected. For example, I have a simple form in my forms.py class SearchForm(forms.Form): province = forms.ChoiceField(choices=PROVINCE, required=False) brand = forms.ChoiceField(choices=BRAND, required=False) price = forms.IntegerField(required=False) In my views.py, I use it in such a way: def search(request) #data - returns data GET or False province = request.GET.get('province', False) brand = request.GET.get('brand', False) price = request.GET.get('price', False) #search engine form = SearchForm(request.GET) query = Car.objects.all() if province: query = query.filter(province=province) if brand: query = query.filter(brand=brand) if price: query = query.filter(price__gtl=price) return render(request, 'searh.html', {'query' :query}) After filling out the form in the template, URL it looks something like this: http://127.0.0.1:8000/search/?brand=Ford&model=&price= Can I show only the fields that have been selected (As below), if so how to do it? http://127.0.0.1:8000/search/?brand=Ford *does not show '&model=&price='because the user has not entered anything I have one more question, I do not know if I can ask them in this topic. If don't I remove them. But how effective is the use of such a queryset (especially with a large number of fields and a large number of objects. Maybe there are … -
How to use forignkey?
I need to issue a book in my library, so when I click on issue, I need to get the book details to the issuer Here Post is the book details and BookIssue is the Issuer's details. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) book_author = models.CharField(default="",max_length=100) publisher = models.CharField(default="",max_length=100) content = models.TextField(max_length=200) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) issued_book_name = models.ForeignKey(BookIssue, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk' : self.pk}) class BookIssue(models.Model): issuer_name = models.CharField(max_length=100,null=False) issuer_email = models.EmailField(max_length=254) issuer_phone_number = models.CharField(default="",max_length=10) issuer_address = models.TextField(max_length=300) issued_book = models.OneToOneField( on_delete=models.CASCADE) def __str__(self): return self.issue_name def get_absolute_url(self): return reverse('blog-home', kwargs={'pk' : self.pk}) -
django inline formset with same parent and child model
I have a Person model which has a parent field which is foreign key to itself, so any instance of this model can have a parent which is another instance of the same model. What I am trying to achieve is to add/update children of a Person using the inlineformsets provided by django. However issue I am having is that inlineformset requires different parent and child models. Models.py from django.db import models # Create your models here. class FamilyMember(models.Model): name = models.CharField(max_length=20) age = models.PositiveIntegerField(null=True, blank=True) job = models.CharField(max_length=20, null=True, blank=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) Views.py def add_child(request): member = FamilyMember.objects.get(name="Tom") child_formset_factory = inlineformset_factory(FamilyMember, FamilyMember, fields=('parent',)) formset = child_formset_factory(instance=member) return render(request, "family/add_child.html", {"formset": formset}) When i render this formset I do not see any children listed for any existing person, even when there are valid records in the db. Instead what I would like to see is this, lets say if a person X has 3 children A, B, C, then I would like to have 3 dropdowns, first dropdown should have A as selected value, second should have B as selected and so on. I am not sure if I am doing it the right way … -
Unable to run bokehjs code because bokehjs library is missing
Id like to embed a graph with bokeh, but I get a page with the unrendered graph on it. home.html <link rel="stylesheet" type="text/css" href="http://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.css"/> <link rel="stylesheet" type="text/css" href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.css"/> <link rel="stylesheet" type="text/css" href="http://cdn.pydata.org/bokeh/release/bokeh-tables-1.3.4.min.css"/> <div class="container text-center"> <h1>HELLO</h1> {{ div }} {{ script }} </div> </body> <script text="type/javascript" src="http://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.js"></script> <script text="type/javascript" src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.js"></script> <script text="type/javascript" src="http://cdn.pydata.org/bokeh/release/bokeh-tables-1.3.4.min.js"></script> <script text="type/javascript" src="http://cdn.pydata.org/bokeh/release/bokeh-api-1.3.4.min.js"></script> views def home(request): x= [1,3,5,7,9,11,13] y= [1,2,3,4,5,6,7] title = 'y = f(x)' plot = figure(title= title , x_axis_label= 'X-Axis', y_axis_label= 'Y-Axis', plot_width =400, plot_height =400) plot.line(x, y, legend= 'f(x)', line_width = 2) #Store components script, div = components(plot) #Feed them to the Django template. return render_to_response( 'bokehApp/home.html', {'script' : script , 'div' : div} ) Result <div class="bk-root" id="5456b4a3-69cc-4962-8afe-31be08905f6b" data-root-id="1001"></div> <script type="text/javascript"> (function() { var fn = function() { Bokeh.safely(function() { (function(root) { function embed_document(root) { var docs_json = '{"ed1a0b2a-1947-447e-8898-9a0c6f7ca346":{"roots":{"references":[{"attributes":{"bottom_units":"screen","fill_alpha":{"value":0.5},"fill_color":{"value":"lightgrey"},"left_units":"screen","level":"overlay","line_alpha":{"value":1.0},"line_color":{"value":"black"},"line_dash":[4,4],"line_width":{"value":2},"render_mode":"css","right_units":"screen","top_units":"screen"},"id":"1045","type":"BoxAnnotation"},{"attributes":{},"id":"1053","type":"Selection"},{"attributes":{},"id":"1054","type":"UnionRenderers"},{"attributes":{"data_source":{"id":"1035","type":"ColumnDataSource"},"glyph":{"id":"1036","type":"Line"},"hover_glyph":null,"muted_glyph":null,"nonselection_glyph":{"id":"1037","type":"Line"},"selection_glyph":null,"view":{"id":"1039","type":"CDSView"}},"id":"1038","type":"GlyphRenderer"},{"attributes":{"source":{"id":"1035","type":"ColumnDataSource"}},"id":"1039","type":"CDSView"},{"attributes":{},"id":"1018","type":"BasicTicker"},{"attributes":{"ticker":{"id":"1013","type":"BasicTicker"}},"id":"1016","type":"Grid"},{"attributes":{"axis_label":"Y-Axis","formatter":{"id":"1044","type":"BasicTickFormatter"},"ticker":{"id":"1018","type":"BasicTicker"}},"id":"1017","type":"LinearAxis"},{"attributes":{"line_color":"#1f77b4","line_width":2,"x":{"field":"x"},"y":{"field":"y"}},"id":"1036","type":"Line"},{"attributes":{"line_alpha":0.1,"line_color":"#1f77b4","line_width":2,"x":{"field":"x"},"y":{"field":"y"}},"id":"1037","type":"Line"},{"attributes":{"axis_label":"X-Axis","formatter":{"id":"1042","type":"BasicTickFormatter"},"ticker":{"id":"1013","type":"BasicTicker"}},"id":"1012","type":"LinearAxis"},{"attributes":{},"id":"1013","type":"BasicTicker"},{"attributes":{"overlay":{"id":"1045","type":"BoxAnnotation"}},"id":"1024","type":"BoxZoomTool"},{"attributes":{"callback":null,"data":{"x":[1,3,5,7,9,11,13],"y":[1,2,3,4,5,6,7]},"selected":{"id":"1053","type":"Selection"},"selection_policy":{"id":"1054","type":"UnionRenderers"}},"id":"1035","type":"ColumnDataSource"},{"attributes":{"label":{"value":"f(x)"},"renderers":[{"id":"1038","type":"GlyphRenderer"}]},"id":"1047","type":"LegendItem"},{"attributes":{},"id":"1025","type":"SaveTool"},{"attributes":{},"id":"1042","type":"BasicTickFormatter"},{"attributes":{},"id":"1027","type":"HelpTool"},{"attributes":{},"id":"1026","type":"ResetTool"},{"attributes":{"dimension":1,"ticker":{"id":"1018","type":"BasicTicker"}},"id":"1021","type":"Grid"},{"attributes":{"items":[{"id":"1047","type":"LegendItem"}]},"id":"1046","type":"Legend"},{"attributes":{},"id":"1023","type":"WheelZoomTool"},{"attributes":{},"id":"1022","type":"PanTool"},{"attributes":{},"id":"1010","type":"LinearScale"},{"attributes":{},"id":"1044","type":"BasicTickFormatter"},{"attributes":{"active_drag":"auto","active_inspect":"auto","active_multi":null,"active_scroll":"auto","active_tap":"auto","tools":[{"id":"1022","type":"PanTool"},{"id":"1023","type":"WheelZoomTool"},{"id":"1024","type":"BoxZoomTool"},{"id":"1025","type":"SaveTool"},{"id":"1026","type":"ResetTool"},{"id":"1027","type":"HelpTool"}]},"id":"1028","type":"Toolbar"},{"attributes":{},"id":"1008","type":"LinearScale"},{"attributes":{"callback":null},"id":"1006","type":"DataRange1d"},{"attributes":{"callback":null},"id":"1004","type":"DataRange1d"},{"attributes":{"text":"y = f(x)"},"id":"1002","type":"Title"},{"attributes":{"below":[{"id":"1012","type":"LinearAxis"}],"center":[{"id":"1016","type":"Grid"},{"id":"1021","type":"Grid"},{"id":"1046","type":"Legend"}],"left":[{"id":"1017","type":"LinearAxis"}],"plot_height":400,"plot_width":400,"renderers":[{"id":"1038","type":"GlyphRenderer"}],"title":{"id":"1002","type":"Title"},"toolbar":{"id":"1028","type":"Toolbar"},"x_range":{"id":"1004","type":"DataRange1d"},"x_scale":{"id":"1008","type":"LinearScale"},"y_range":{"id":"1006","type":"DataRange1d"},"y_scale":{"id":"1010","type":"LinearScale"}},"id":"1001","subtype":"Figure","type":"Plot"}],"root_ids":["1001"]},"title":"Bokeh Application","version":"1.3.4"}}'; var render_items = [{"docid":"ed1a0b2a-1947-447e-8898-9a0c6f7ca346","roots":{"1001":"5456b4a3-69cc-4962-8afe-31be08905f6b"}}]; root.Bokeh.embed.embed_items(docs_json, render_items); } if (root.Bokeh !== undefined) { embed_document(root); } else { var attempts = 0; var timer = setInterval(function(root) { if (root.Bokeh !== undefined) { embed_document(root); clearInterval(timer); } attempts++; if (attempts > 100) { console.log("Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing"); clearInterval(timer); } }, 10, root) } })(window); }); }; if … -
pictures unlimited for each list
I want to solve the problem for an unlimited number of pictures for each list. Whenever I want to put the pictures on the list, I get only one picture or i write several fields for the picture. Note: Photos are added at the same time as the list I try define ForeignKey for picture and then store file in session class Listing(models.Model): title = models.CharField(max_length=200) address = models.CharField(max_length=200) class Photo(models.Model): image = models.ImageField(default="default.png", blank=True, null=True, upload_to="photos/%Y/%M/%D") listing = models.ForeignKey(Listing, related_name='Photos', on_delete=models.CASCADE) Is it possible to add files on the session and then refer to them later after save the list because He didn't accept wanting to turn the object into json if request.method == "POST": myfile = request.FILES['file'] if 'file' in request.FILES else False if myfile: if not 'saved' in request.session or not request.session['saved']: request.session['saved'] = [json.dumps(str(myfile))] else: request.session['saved'].append(json.dumps(str(myfile))) -
How to get google calendar events of users of my website by python
I want to get google calendar events of users of my website by python and django. I used the following code but it gets just my events of google calendar. How can I access to google calendar of users if I hare 'user' in the input of the following 'def' to get and insert event to it (any user have a email field)? from __future__ import print_function import datetime import json import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request def get_events_google_calendar(): """Shows basic usage of the Google Calendar API. Prints the start and name of the next 10 events on the user's calendar. """ # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] creds = None # The file token.pickle stores the user's access and refresh tokens, and # is created automatically when the authorization flow completes for the first time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( './google_calendar/client_secret.json', SCOPES) creds = flow.run_local_server(port=0) # Save the … -
How to Test in case Unittest By pass file excel to Import API
i'm will test code by TestCase of django.test and APIClient of resrt_framework.test with excel file, where do i can test thus import api test_import_file.py import xlrd from django.test import TestCase from rest_framework.test import APIClient from account.models import Account from account.tests import create_super_user from instructor.models import Instructor from utils.excel import get_value class TestClassImport(TestCase): def setUp(self): self.account = create_super_user() self.client = APIClient() self.client.force_authenticate(self.account) self.url = 'static/example/example_class_import.xlsx' self.file = open('static/example/example_class_import.xlsx', 'rb') self.wb = xlrd.open_workbook(file_contents=self.file.read()) self.sh = self.wb.sheet_by_index(0) def test_real_import(self): file = open(self.url, encoding="utf8", errors='ignore') url = '/api/dashboard/content-migration/import/instructor/' self.response = self.client.post(url, file) self.failUnlessEqual(self.response.status_code, 201) I hope it will "test_real_import (class.unittest.test_import_file.TestInstructorImport) ... ok" -
How do i turn off django's plural notation in the admin page
I have some tables that are presented as inlines of another class. I have altered the default title of these inline representations by adding an inner class to the respective tables. class Meta: verbose_name = 'Binnengekomen punten' I have only the verbose_name defined but it still adds an s to all the names. So 'Binnengekomen punten' is displayed as 'Binnengekomen puntens' What i could do is define the plural of verbose_name verbose_name_plural the same as verbose_name. But is there a way to simply turn off the plural notation? I'd love to know thank you. -
How to populate (Chained) Dependent Dropdown
I want to populate dependent combos based on selection of parent combos. my code is as follow: class Species(models.Model): name = models.CharField(max_length=120, blank=False, null=False) description = models.TextField(max_length=300, blank=False, null=False) class SpeciesDetail(models.Model): species = models.ForeignKey(Species, on_delete=models.CASCADE) picture = models.ImageField(upload_to='pics') gender = models.CharField(max_length=1) health = models.CharField(max_length=120) class Pair(models.Model): species = models.ForeignKey(Species, on_delete=models.CASCADE) male = models.ForeignKey(SpeciesDetail, on_delete=models.CASCADE, related_name='male_set') female = models.ForeignKey(SpeciesDetail, on_delete=models.CASCADE, related_name='female_set') -
How to resize image file in django model
I have a model with an ImageField . I would like to add a save method in the model to resize image before saving. I got the code to work without throwing any error. But the image file was not resized. I tried put the same code in views.py and uploaded images are resized correctly. Wonder what I did wrong I am using python 3.7 with django 2.2. model.py class UploadFile(models.Model): image_file_path = models.ImageField(upload_to='images/', null=True, blank=True) def save(self, *args, **kwargs): Img.MAX_IMAGE_PIXELS = 933120000 if self.image_file_path: image = Img.open(self.image_file_path) (width, height) = image.size print(width,height) # "Max width and height 800" if (800 / width < 800 / height): factor = 800 / height else: factor = 800 / width size = (int(width * factor), int(height * factor)) resized_image = image.resize(size, Img.ANTIALIAS) image.close() file_path = os.path.join(settings.MEDIA_ROOT, str(self.image_file_path)) resized_image.save(file_path,optimize=True,quality=95) return super(UploadFile, self).save(*args, **kwargs) -
Best way to store measurement units for Django model's fields?
I have a product model which has a lot of fields with all the product's specs such as width, weight, and a lot of other. I want to display a table with all specs, so I decided to iterate through my model's fields and display the table with a field name + value + measurement units in my template. I'm storing field name in a verbose_name attribute and field description in the help_text attribute, but I'm curious what is the best way to store a particular measurement unit for a specific field? -
Django migrations: what `elidable` argument is for?
I have a RunPython operation in my migrations. This operation accpets an optional elidable argument, which is described in the Django docs: The optional elidable argument determines whether or not the operation will be removed (elided) when squashing migrations. This description is a little bit confusing for me. My question is: what happens, when migrations with elidable=True flag are squashed? I guess that migrations with elidable=True would be simply deleted. And some manual steps would have to be taken in order to add the logic of elided migrations into the squashed one. -
Able to upload file but non retrieve them - Page not found
I am creating a website in Django and Postgres where a user can answer multiple questions and upload some PDFs. I am able to upload the PDF but not to display it. I want the user to be able to click on a link, and a new webpage opens containing the PDF. In my details.html I wrote the code: <a href="{{ MEDIA_URL }}{{project.thirdquestiondetail.third_seven.url}}">Click here to see the file</a> But, if the user clicks on the links, he gets this messages: I have the following: mysite/urls.py from django.contrib import admin from django.urls import path, include from django.views.generic.base import TemplateView from django.conf import settings from django.views.static import serve from django.conf.urls.static import static urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('conditions/', TemplateView.as_view(template_name='conditions.html'), name='conditions'), path('admin/', admin.site.urls), path('users/', include('users.urls')), path('users/', include('django.contrib.auth.urls')), path('projects/', include('projects.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) mysite/settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'mysite/static/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' As said, I am pretty sure the PDF is uploaded. In fact, if I login as superuser in the admin panel, I can see the PDF. HOWEVER if I click it, I get the same 404 error reported above I think the error is in my settings.py when … -
Django set M2M field similar to other M2M field
I have a problem with Many-to-Many Fields. In a post-save hook I am trying to set a Many-to-Many Field. I basically want to copy another M2M field and save it into the new one. class A(models.Model): a = ManyToManyField(X, ...) class B(models.Model): b = ManyToManyField(X, ...) @receiver(post_save, sender=B, dispatch_uid="uid") def postsave_it(sender, instance, **kwargs): if not instance.b.exists(): post_save.disconnect(...) instance.b.set(instance.a) post_save.connect(...) So the line instance.b.set(instance.a) doesnt work, the instance of A has no value for a selected. Help would be very much appreciated! -
Cannot import <app>. Check that <path> is correct
I have a next structure of project I want to create a signal in a blog application, but I get an error Cannot import 'blog'. Check that 'project.blog.apps.BlogConfig.name' is correct. If I write default_app_config = 'blog.apps.BlogConfig' in __init__.py I get error: No module named 'blog' settings.py INSTALLED_APPS = [ #... # project apps 'project.blog', #... ] apps.py class BlogConfig(AppConfig): name = 'blog' def ready(self): import blog.signals __init__.py default_app_config = 'project.blog.apps.BlogConfig' -
I got this error "Tuple has no attribute 'obj'"
I got this error "Tuple has no attribute 'obj'" def upload_list(request): pdf = Client_files.objects.all() cn = pdf.values_list('client').distinct() print(cn) for i in range(len(cn)): client = Client_Process.objects.filter(client__in=cn[i]) cn[i].obj = client -
Is there a more elegant way to write this django view?
I've been messing around with django and I have this django view: def handle_results(request): if request.method == "POST" and request.is_ajax(): # Do something with the post request elif request.method == "GET" and request.is_ajax(): # Do something with the get request else: # First time in this view, render first element to display return render( request, "result_page.html", context={"display": arr[0]} ) The main idea is, this is supposed to be a Same Page Application, and the first time I'm in this view, I need to render the contents of the array to display to the user, after that, the user can interact with said array via the html (think of it as upvoting or downvoting stuff that's shown). Depending on the user's choice, I get a GET or POST request and need to deal with said request. However, the way I'm implementing this seems not that elegant and I was wondering if there'd be another better way to accomplish what I'm doing. Thank you so much! -
the website created is for editing images with frames
the django website i have created is not saving any of the images that i choose neither it is displayed on the frame whc i select.. this is my views.py def SaveProfile(request): saved = False if request.method == "POST": # Get the posted form MyProfileForm = ProfileForm(request.POST, request.FILES) if MyProfileForm.is_valid(): profile = Profile() profile.name = MyProfileForm.cleaned_data["name"] profile.picture = MyProfileForm.cleaned_data["picture"] profile.save() saved = True else: MyProfileForm = Profileform()class Profile(models.Model): name = models.CharField(max_length = 50) picture = models.ImageField(upload_to = 'media') class Meta: db_table = "profile" return render(request, 'saved.html', locals()) this is models.py class Profile(models.Model): name = models.CharField(max_length = 50) picture = models.ImageField(upload_to = 'media') class Meta: db_table = "profile" this is forms.py class ProfileForm(forms.Form): name = forms.CharField(max_length = 100) picture = forms.ImageFields() i cannot save o display the chose image from the form neither i can download -
Detail page with Tag and Slug not found DJANGO
I am currently going through a django book and learning how to use Tags. It works fine but unfortunately whenever I want to access the detail page, the terminal return not found. I have checked several times and not able to find what the issue is. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='published') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() # Tag manager tags = TaggableManager class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.year, self.slug]) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return 'Comment by {} on {}'.format(self.name, self.post) urls.py from django.contrib import admin from django.urls import path, include from . import views app_name = 'blog' urlpatterns = … -
how can i solve this using django
Traceback (most recent call last): File "C:/Users/siva/PycharmProjects/mtech2/mysite/oms.py", line 1, in import omsFunctions File "C:\Users\siva\PycharmProjects\mtech2\mysite\omsFunctions.py", line 1, in import nltk File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\site-packages\nltk__init__.py", line 99, in from nltk.internals import config_java File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\site-packages\nltk\internals.py", line 11, in import subprocess File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 126, in import threading File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 8, in from traceback import format_exc as _format_exc File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\traceback.py", line 5, in import linecache File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\linecache.py", line 11, in import tokenize File "C:\Users\siva\AppData\Local\Programs\Python\Python37-32\lib\tokenize.py", line 41, in all = token.all + ["tokenize", "detect_encoding", AttributeError: module 'token' has no attribute 'all' Process finished with exit code 1