Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Loop through items before rendering pdf and populating table using pdfkit and Django
I'm trying to export all of my users and data related to them in a rendered pdf. I'm struggling to loop over all my users and creating new table rows for each user. As per now the loop loops over all users, but it only populates the table with the data of the last user registered. I do not think I'm able to use Django's conventional way of for looping, at least I cannot figure out how to pass context to the template. views.py def usersExport(request): users = User.objects.all() # populate template tags in generated pdf with data data = dict() for user in users: data['full_name'] = user.get_full_name # getting template, and rendering data template = get_template('backend/users/users_export.html') html = template.render(data) pdf = pdfkit.from_string(html, False) #function for creating file name def create_file_name(): file_name = 'users %s.pdf' % (timezone.now()) return file_name.strip() filename = create_file_name() response = HttpResponse(pdf, content_type = 'application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response users_export.html <table> <tr class="thead"> <th class="text-left">Name</th> </tr> <tr> <td class="text-left">{{ full_name }}</td> </tr> </table> -
How to add a sub-app in django to INSTALLED_APPS?
I have the structure of my project: project ———— project ———— app ———————— subapp ———— manage.py I added my sub-app to INSTALLED_APPS like that: INSTALLED_APPS = ['app.apps.AppConfig', 'app.subapp.apps.SubapConfig'] But it doesn't works. Django gives me an error message: No module named 'news' and Cannot import 'news'. Check that 'apps.subapp.apps.SubapConfig.name' is correct. -
URL http://localhost:8000/admin/ redirects to wrong page
I'm trying to reach the Django admin page but when I type in http://localhost:8000/admin/ it pops up with my web application instead. For more context I have two url.py's in separate folders. from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.project_list, name='list'), path('<slug:project_slug>/', views.project_detail, name='detail') ] and... from django.urls import path, include urlpatterns = [ path('', include('budget.urls')), path('admin/', admin.site.urls), I'm not sure why http://localhost:8000/admin/ doesn't go to Django's admin page but if anyone has any suggestions that would be very much appreciated. -
URL not found for updateview with polymorphic models and forms in Django
I am trying to display all the models that are related to another model in a modal box when a user clicks on a button. However, the Update view is not working how I want it to work. I am getting a Not Found for the URL pattern related to the class based view (Model Object UpdateView) instead of 200 OK I tried several approaches, but below is the latest one. When I do a print out of the get_queryset (that I have override), I get the objects. I tried to print the context['formset'], but it seems like the code didn't reach that far. I am using django-bootstrap-modal-forms 1.4.2 to display model formsets and I am using django-polymorphic 2.1.2 to deal with polymorphism of the models. forms.py - I create the two forms based on the WebPageObject & LinkObject both inherits from ModelObject (a polymorphic model) I then created a polymorphic modelformset. class ModelWebPageObjectForm(ModelForm): class Meta: model = WebPageObject fields='__all__' class ModelLinkObjectForm(ModelForm): class Meta: model = LinkObject fields = '__all__' Oformset = polymorphic_modelformset_factory(ModelObject,formset_children=( PolymorphicFormSetChild(WebPageObject, form=ModelWebPageObjectForm, fields = '__all__'),), fields='__all__',extra=1) PolymorphicFormSetChild(LinkObject, form=ModelLinkObjectForm, fields = '__all__'), views.py - In this view, I have a used the ModelObject (a polymorphic model) as the … -
Connecting Mysql database in my django project has become a pain as i have tried all the available methods and its not working
Administrator: Windows Powershell Codes: (projectsenv) PS C:\users\amarn\onedrive\desktop\projects\projectsenv> pip install mysqlclient==1.3.12 Collecting mysqlclient==1.3.12 Downloading https://files.pythonhosted.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.12.tar.gz (89kB) |████████████████████████████████| 92kB 203kB/s Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\amarn\onedrive\desktop\projects\projectsenv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\amarn\AppData\Local\Temp\pip-install-tz4hbi8_\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\amarn\AppData\Local\Temp\pip-install-tz4hbi8_\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\amarn\AppData\Local\Temp\pip-wheel-9tefdy3z' --python-tag cp37 cwd: C:\Users\amarn\AppData\Local\Temp\pip-install-tz4hbi8_\mysqlclient\ Complete output (25 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.7 copying _mysql_exceptions.py -> build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\amarn\onedrive\desktop\projects\projectsenv\scripts\python.exe' -u … -
Updating highcharts data in django via ajax
I'm running into errors with rendering my highcharts chart via data from the db and can't seem to figure out why Here's the code (document).ready(function() { var options = { chart: { renderTo: 'chart_panel3', type: 'scatter', zoomType: 'xy' }, legend: { enabled: false }, tooltip: { formatter: function () { return "<br/><br/> " + "Date: " + this.x + "<br/><br/> " + "Yr: "+ this.y + "<br/><br/>" + contact_notes3[this.point.index]; }}, xAxis: { gridLineWidth: 0, type: 'datetime', dateTimeLabelFormats: { day: '%m/%d' } }, yAxis: { gridLineWidth: 0, plotLines: [ { value:2019, color: 'grey', width: 0.5}, { value:2018, color: 'grey', width: 0.5}, { value:2017, color: 'grey', width: 0.5}, ] }, plotOptions: { column: { dataLabels: { enabled: true } } }, series: [{}], }; var chartDataUrl3 = "{% url 'chart_data3' pk %}" var contact_notes3 = []; $.getJSON(chartDataUrl3, function(data) { options.xAxis.categories = data['chart_data']['contact_date']; options.series[0].name = 'somename'; options.series[0].data = data['chart_data']['other']; contact_notes3 = data['chart_data']['contact_notes']; var chart = new Highcharts.Chart(options); }); // FYI- this works if I were to uncomment the next set of lines It looked to me that the chart_data3 url endpoint being referenced by chartDataUrl3 may be where the error is coming up, but when I go to the url directly, I get … -
How to generate download link django-oscar
I'm setting up digital shop using Django oscar, it's all well and fine but, I'm trying to figure out how to add a download link. Because of the way django-oscar was set up, each product have AbstractProductAttribute that is related to a ProductClass what I want to do is add a link to thank you page for the download after payment process anyone done this before I need help getting the file attribute of the AbstractProductAttribute thank you. -
DjangoREST vs ExpressJS , which 1 should I choose to build REST API?
I want to build REST API (or GraphQL API) which I want to connect with Angular (2+) to build some nice web application. Which framework should I choose to get started with and why? DjangoREST or ExpressJS ? Which one of them is easier to get connected with front-end frameworks? I know python as well as JavaScript. I also have experience with django as well as some JavaScript front-end frameworks like Angular. So, it wouldn't be that difficult to get started with nodejs or either of them. Which of then is easier and better? -
How to properly link SCSS using PythonAnywhere?
I am currently working on revamping my portfolio, so I decided to switch fully to SCSS instead of CSS. Now even before when I commit from PyCharm I always need to edit it a little bit, to make it work in PythonAnywhere. The explanation: This is the code I use to make it work in PyCharm TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' Now to make this work in PythonAnywhere I have to edit above code to this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['portfolio/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] MEDIA_ROOT = u'/home/Gromis/portfolio/media' MEDIA_URL = '/media/' STATIC_ROOT = u'/home/Gromis/portfolio/static' STATIC_URL = '/static/' I think that is the issue why I can't properly link SCSS file, is because of the wrong path in settings.py . I get this error now while loading the website: Unable to locate file scss/style.scss while rendering tag 'sass_src' in template project_index.html Of course, the same code works perfectly in PyCharm, so … -
Django Black Not Installing Properly
I received an error after installing Django Black. I ran "pipenv install black --pre". Then when I ran manage.py runserver, I received the error below. Note that I am running Windows 10. from custom_storages import MediaStorage File "C:\Users\dgold2\Documents\py\ibankai\src\custom_storages.py", line 2, in <module> from storages.backends.s3boto3 import S3Boto3Storage File "C:\Users\dgold2\Documents\py\ibankai\src\.venv\lib\site-packages\storages\backends\s3boto3.py", line 18, in <module> from django.utils.six.moves.urllib import parse as urlparse ModuleNotFoundError: No module named 'django.utils.six' -
Invalid URL. Django
I created search form: <form action="{% url 'search_results' %}" method="get"> <div class="row"> <div class="col-lg-8 col-md-6 col-xs-12"> <input name="q" type="text" placeholder="Search..." class="form-control"> </div> <div class="col-lg-3 col-md-6 col-xs-12"> <select name="q2" class="form-control" id="exampleFormControlSelect1"> <option>All locations</option> <option>Москва</option> <option>Петербург</option> <option>Казань</option> </select> </div> <div class="col-lg-1 col-md-6 col-xs-12"> <!-- <button> Search </button> --> <button class="btn btn-primary">Primary</button> </div> </div> </form> When I input "c++" I go to http://127.0.0.1:8001/search/?q=c%2B%2B&q2=%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0 (Result is OK, but '+' is interpreted as %2B) When I click pagination "next" I receive http://127.0.0.1:8001/search/?vacancy=2&q=c++&q2=%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0 (ERROR Page not found) I need http://127.0.0.1:8001/search/?vacancy=2&q=c%2B%2B&q2=%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0 How can I fix this (convert '+' to '%2B')? vacancy_list.html {% extends 'vacancy_list/base.html' %} {% block content %} <div class="container " style="margin:20px;"> <!-- wrapper for all containers --> <div class="container" style="margin-top: 40px; font-size: 2rem;"> <form action="{% url 'search_results' %}" method="get"> <div class="row"> <div class="col-lg-8 col-md-6 col-xs-12"> <input name="q" type="text" placeholder="Search..." class="form-control"> </div> <div class="col-lg-3 col-md-6 col-xs-12"> <select name="q2" class="form-control" id="exampleFormControlSelect1"> <option>All locations</option> <option>Москва</option> <option>Петербург</option> <option>Казань</option> </select> </div> <div class="col-lg-1 col-md-6 col-xs-12"> <!-- <button> Search </button> --> <button class="btn btn-primary">Primary</button> </div> </div> </form> </div> {% for vacancy in vacancies %} <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-8"> <h1><a href="{% url 'vacancy_detail' pk=vacancy.pk %}">{{vacancy.title}}</a></h1> </div> <div class="col-md-4 text-right"> <p> {{ vacancy.salary}} </p> </div> </div> </div> <div class="card-body" … -
Django CMS CSS trouble?
Im trying to style a plugin in my Django-CMS project ( django 1.11, CMS 3.6.0 ). Im trying to add my class to my plugin html, like this : <div class="question"> <h1 class="question-title">{{ instance.poll.question }}</h1> <form action="{% url 'polls:vote' instance.poll.id %}" method="post"> {% csrf_token %} <div class="form-group"> {% for choice in instance.poll.choice_set.all %} <div class="radio"> <label> <input type="radio" name="choice" value="{{ choice.id }}"> {{ choice.choice_text }} </label> </div> {% endfor %} </div> <input type="submit" value="Vote" /> </form> </div> Then I go into my css, and try to apply some styles to the plugin, but nothing happens. When I inspect my div which should have a class of "question" in the browser, there is no class even though I specified it in my html. Why is that ? When I do something like : body { width: 1060px; margin: 10px auto; } It applies the styles correctly. Anybody knows what is happening here ? Where are my custom classes from the html ? I was trying to find a guide on Django-CMS and styling, but Im not having much luck. Thank you guys ! -
Passing data from external python script in django to swift
Trying to create a swift request where an external python script is run in Django and returns data to the user. I just cant wrap my head around on what best practices there are or on how to do this. Any help would be appreciated. Python script returns print(output) Djano views.py def post(self, request, *args, **kwargs): self.create(request, *args, **kwargs) inp = request.FILES.get('image').name out = run([sys.executable,'//Users//macbookpro//TestAPI//venv//Test_Script.py',inp],shell=False,stdout=PIPE, text= True) print(out.stdout) return Response ({"output": str(out)}) Swift to: REST_UPLOAD_API_URL, headers: headers, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in debugPrint(response) print(stdout) What would be the best way to pass data from the Python script and back to the user? Do i need to create a JSON response in Django and afterwards Decode it in Swift? If so, how would that work? If not, then how can you decode the "stdout" response in Swift which I'm currently receiving. Results so far: print(out.stdout) gives me the desired text response within Django DebugPrint(response) = Returns desires text --> stdout='MyDesiredText\n')"; print(stdout) in Swift gives me = 0x000000010a45d1a8 -
Django file not uploading: ValueError at / The 'image' attribute has no file associated with it
I created a form with django forms. I implemendted on html page. Everything is ok but my image not uploaded on database. I was trying to find issue. I tried print(request.FILES) It returned <MultiValueDict: {}> I understood my uploaded image didn't upload correctly im my database. Though form was submitted and when I tryied to query from product it will get error ValueError at / The 'image' attribute has no file associated with it. this is my traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.5 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'product.apps.ProductConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/asad/PycharmProjects/eShop/templates/base.html, error at line 8 The 'image' attribute has no file associated with it. 1 : {% load staticfiles %} 2 : <!DOCTYPE html> 3 : <html lang="en"> 4 : <head> 5 : <meta charset="UTF-8"> 6 : <title>{% block title %}{% endblock %}</title> 7 : <!-- Latest compiled and minified CSS --> 8 : <link rel="stylesheet" href="https://maxcd n.bootstrapcdn.com/ bootstrap/4.3.1/css/bootstrap.min.css"> 9 : 10 : 11 : </head> 12 : <body> 13 : 14 : <div class="container"> 15 : <div class="row"> 16 : <div class="col-md-4"> 17 : <a … -
How to save foreign from html form (select)?
I can not save the appropriate value for ForeignKey from the form. The value of ForeignKey is always written to the database, with id = 1. in html form the values from my model, which is in the database, are output to the select. But when sending data from the form, the values of the fields for which the type of foregonekey are written to the database all the time by id = 1 models.py: class Sportsman(models.Model): first_name = models.CharField(max_length=64, blank=True, null=True, default=None, verbose_name='Имя') last_name = models.CharField(max_length=64, blank=True, null=True, default=None, verbose_name='Фамилия') gender = models.ForeignKey(Gender, on_delete=models.CASCADE, null=True, blank=True, default=True, verbose_name='Пол') tournament = models.ForeignKey(Tournament, null=True, blank=True, default=True, on_delete=models.CASCADE, verbose_name='Турнир') def __str__(self): return "Спортсмен(ка): %s %s, почта: %s" % (self.first_name, self.last_name, self.email) class Meta: verbose_name = 'Спортсмен' verbose_name_plural = 'Спортсмены' def save(self, *args, **kwargs): super(Sportsman, self).save(*args, **kwargs) forms.py: class SportsmenForm(forms.ModelForm): class Meta: model = Sportsman exclude = ['created', 'updated'] views.py: def sportsman(request): documents = Document.objects.filter(is_active=True) form = SportsmenForm(request.POST or None) if request.method == "POST" and form.is_valid(): print(request.POST) print(form.cleaned_data) print(form.cleaned_data['email']) form.save() new_form = form.save() return render(request, 'sportsman/sportsman.html', locals()) <QueryDict: {'csrfmiddlewaretoken': ['BzBeiKE82LDcd3tmdzZGSmpOWQatc52SSO7ScEOm7eCVdXsHQWxerSzTZa6KC5xq'], 'first_name': ['test_name'], 'last_name': ['test_name'], '<select name=': ['3']} > -
Adding 'only' before prefetch related slows down query
In pseudocode, I have a db model like this: Model T name tags = models.ManyToManyField(Tag, related_name="Ts") symbol = models.ForeignKey(Symbol) Model Symbol name category = models.ForeignKey(Category) Model Tag name And this is the code I use to export it: query = T.objects.annotate(category=F('symbol__category')).prefetch_related('tags') for t in query: _dict = model_to_dict(t) _dict["category"] = t.category _tags = [] for tag in _dict["tags"] _tags.append(tag.id) _dict["tags"] = _tags In this code, _dict gives me the wanted result. However, T has many other fields I don't need, so I changed query to: T.objects.only("name", "symbol", "tags").annotate(category=F('symbol__category')).prefetch_related('tags') For some reason, this slows down the execution. Original query takes 6 seconds while the last one takes 8 seconds. Why? How can I prefetch everything correctly so that I don't have to loop over tags and append their ids in a dictionary? How can I do this while also using .only()? -
Django rest-auth registration error after creating new user. account_confirm_email not found
I am creating a registration system with Django rest-auth and allauth. Looking at the documentation endpoints, I just used: urls.py app_name = "apis" urlpatterns = [ path('users/', include('users.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/customlogin', CustomLoginView.as_view(), name='rest_login'), path('rest-auth/customlogout', CustomLogoutView.as_view(), name='rest_logout'), path('rest-auth/registration/', include('rest_auth.registration.urls')), ] when I run, a browseable API appears like below: After entering the details and post it, the below error occurs: django.urls.exceptions.NoReverseMatch: Reverse for 'account_confirm_email' not found. 'account_confirm_email' is not a valid view function or pattern name. is there another URL i need to implement (with the name of account_confirm_email) ? I have read the documentations and rest-auth demos on this and it seems I need to include the following urls: url(r'^verify-email/$', VerifyEmailView.as_view(), name='rest_verify_email'), url(r'^account-confirm-email/(?P<key>[-:\w]+)/$', TemplateView.as_view(), name='account_confirm_email'), but this still did not fix the error why is that? -
AttributeError: module 'tagulous' has no attribute 'models' in Django
So I have been building a web app, and for the tags system, I decided to go with django-tagulous. However, when I import it in my models, I am getting this error: AttributeError: module 'tagulous' has no attribute 'models' in Django I have put it in my python INSTALLED_APP list in settings.py, and imported it in models.py, but still get the error. Here is some code. models.py import tagulous class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=75) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to='post_images',blank=True,null=True) published_date = models.DateTimeField(blank=True,null=True,auto_now_add=True) NSFW = models.BooleanField(default=False) spoiler = models.BooleanField(default=False) interests = tagulous.models.TagField() tags = TaggableManager() def __str__(self): return self.title def save(self, *args, **kwargs): super().save(*args, **kwargs) In that Post class, I am using this on the interests one. Here is my forms.py PostForm class PostForm(forms.ModelForm): class Meta(): model = Post fields = ['title','text','image','interests','spoiler','NSFW'] widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'textareaclass editable'}), } def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['image'].required = False So far I have found nothing online about this error. I was expecting it to work, but it didn't Thanks :) -
How to customize the submit and verification method of Django forms?
I've been making my blog project with Django and I was tryting to implement Toast UI Text Editor README, a kind of open source text editor which be be loaded on client web pages. What I'm considering was to locate the text editor inside my form, however, If I do that, I have to remove the CharField named content(which is to be replace with the content of text editor) from forms.py and have to customize sumbit method. But the problem is I don't know how to customize the form submit method or verification method. What I want to do is use the default verification method on client side and if it tells the input is valid, then submit the form data added the content text editor. this is my code. class ArticleCreationForm(forms.Form): do_you_wanna_get_emails = forms.ChoiceField( choices = ( ('option_one', "YES. I wanna get an email once someone reply to you"), ('option_two', "NO. I don't need to get an email.") ), widget = forms.RadioSelect(), initial = 'option_two', ) title = forms.CharField() name = forms.CharField() password = forms.CharField( widget=forms.PasswordInput(), help_text = "Here's more help text" ) email = forms.CharField() ### I removed this field to replace this with the content of Toast … -
DJANGO - upload image stored locally to model ImageField attribute
I have my images downloaded inside the subroot images in my media folder and I'm trying to generate new models which will contain the photo inside the images folder. This is what my model and my view look like: class Post(models.Model): ... image = models.ImageField(upload_to="images", blank=True, null=True) def generate_posts(request): for i in range(20): title_ = f'title{i}' body_ = f'text for post number : {i}' author_ = f'author{i}' network_ = randomize_social() post = Post(title=title_, body=body_, author=author_, social_network=network_) if randomize_picture(): post.image.save("logo.png", File("images/svante.jpg"), save=True) else: post.image = None post.save() areGenerated = True return render(request, "posts/generate_posts.html", {'areGenerated':areGenerated}) The logo.png file is created inside the images folder, but it's blank, 0kb size and when I follow the /generateposts url, I receive this error message: AttributeError at /generateposts 'str' object has no attribute 'read' What can I do to solve this problem? -
how can achieve to Intended query set by this models in django
I have Post model: class Post(models.Model): description = models.CharField( max_length=1500, blank=True, ) school = models.ForeignKey( 'school.School', on_delete=models.CASCADE, null=True ) sibling_uuid = models.CharField(max_length=36, null=True) create_date = models.DateTimeField(default=timezone.now) if Post objects belong to school the sibling_uuid will be random uuid.uuid4 and i will create a post for every class of this school a Post instance with same sibling_uuid . by this way i will know which post should be remove if school's manager removing a school's post.but if i want return a school post to school's manager i need just return one of post per sibling post.(means that from Posts with same sibling_uuid just one of them should be in query set).i'm doing by this way now: school_posts = Post.objects.filter(school__isnull=False).distinct('sibling_uuid') # from every sibling post just on will exist in school_posts classroom_posts = Post.objects.filter(school__isnull=True) all_posts_queryset = sorted(chain(classroom_posts, school_posts), key=attrgetter('create_date'), reverse=True) i want doing above code in a single line to my code be cleaner and i learn ORM better. thank you. -
How to get model from plugin?
My model: class Post(models.Model): title = models.CharField(max_length=100) short_description = models.CharField(max_length=100) image = models.ImageField(upload_to="uploads/images/") content = HTMLField(blank=True) slug = AutoSlugField(always_update=True,populate_from='title', unique=True) date_created = models.DateField(default=datetime.date.today()) CMS Plugin: class PostPlugin(CMSPlugin): post = models.ForeignKey(Post, on_delete=models.CASCADE) Register plugin: @plugin_pool.register_plugin class CMSPostPlugin(CMSPluginBase): model = PostPlugin name = _("Post") render_template = "post/post.html" allow_children = True admin_preview = True module = "subpage" def render(self, context, instance, placeholder): context.update({ 'post':instance.post, 'instance':instance, 'placeholder':placeholder }) return context So, after that, I add this to my table, the intermediate table was created. Here a screenshot. table screenshot So that how I get the plugins: CMSPlugin.objects.filter(plugin_type='CMSPostPlugin', placeholder_id=placehoder.id) after that, I want to get the Post model from this intermediate table, but I don't know how to do that. -
How to return values from database/model after post request in Django Rest framework
I recently started working on django. I am trying to send a location name via post method and then display the list of values from the model on the url or api end point. I am unable to do it. When I send a post request I am not able to view the results on the url/api end point. It displays GET menthod not allowed. This is my views.py class location_details(APIView): def post(self, request, *args, **kwargs): event_id = json.loads(request.body).get('location_name') queryset = customer.objects.filter(eid= event_id) serializer_class = customer_details data = serializers.serialize('json', queryset) return HttpResponse(data, content_type='application/json') How can I display the values based on a post request? I am stuck with this issue for a long time. -
Django admin anotate not work with change list view queryset
I need to create a summary view for a list of records grouped by year, month and category. When I use the model manager and do annotating it works fine, and summary is correctly created. However, if I use the changelist_view request objetcts' queryset it duplicate ungrouped records as well. See the two code listings below. Correct Values: Bill.objects.values_list('category__name', 'year', 'month').annotate(Sum('amount'), due=Sum(F('amount') - F('paid_amount'), output_field=models.FloatField())) <QuerySet [('Insurance', '2019', 'FEB', Decimal('35200.2300000000'), 25200.230000000003), ('Telephone', '2019', 'AUG', Decimal('3353.54000000000'), -23.0), ('Telephone', '2019', 'JUL', Decimal('200'), 200.0)]> Incorrect when used with changelist_view queryset: qs = response.context_data['cl'].queryset extra_context['summary'] = qs.values_list('category__name', 'year', 'month').annotate( Sum('amount'), due=Sum(F('amount') - F('paid_amount'), output_field=models.FloatField())) print(extra_context['summary']) <QuerySet [('Telephone', '2019', 'AUG', Decimal('1677'), -23.0), ('Telephone', '2019', 'JUL', Decimal('500'), 500.0), ('Telephone', '2019', 'AUG', Decimal('1676.54000000000'), 0.0), ('Telephone', '2019', 'JUL', Decimal('-300'), -300.0), ('Insurance', '2019', 'FEB', Decimal('35200.2300000000'), 25200.230000000003)]> Above see that AUG 2019 not grouped correctly. -
What is {% url %} in django?
I have django template: <form id="contactForm" method="get" action="{% url 'contact-form' %}"> ... </form> What is {% url 'contact-form' %} ?