Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use authentication in templates and vue.js together
I have mature Django application that is built with Django-templates for the frontend. Now I want to rewrite part of the application to Vue.js (user's dashboard). That is, I want use the Django-Rest-Framework for the backend and Vue.js for the frontend, but not use Django templates at all. Is it possible to somehow combine the authentication that is used in Django templates in the frontend, written in Vue.js? That is, so that the frontend, written in Vue.js, receives information whether the user is authenticated or not. -
How the change the underlying model for a form in a view?
I have a small Django-app were I want to manage two stock portfolios. I created two tables (SecuritiesSVR and SecuritiesAHT) with the same structure (based on an abstract model). In the url I added an argument 'ptf' : portfolio/str:ptf/change_position I also created a form to update the tables: class SecuritiesUpdateForm(forms.ModelForm): class Meta: model = model is dependent on parameter in url fields = ['opinions', 'remarks'] Now i'm searching for a way to change the underlying model for the form depending on the parameter in the url: def change_position(request, ptf, symbol): if ptf == 'aht': Securities = SecuritiesAHT if ptf == 'svr': Securities = SecuritiesSVR security = Securities.objects.get(pk=symbol) if request.method == 'POST': u_form = SecuritiesUpdateForm(request.POST, request.FILES, instance=security) if u_form.is_valid(): u_form.save() messages.success(request, f'Security has been updated!') return redirect('portfolio:portfolios', ptf=ptf) else: u_form = SecuritiesUpdateForm(instance=security) context = { 'u_form': u_form, 'ptf': ptf } return render(request, 'portfolio/change_position.html', context) Is there a possibility to set in the view the model that the form needs to use? -
GET Request Django Rest Framwork: Not able to access static folder
I am developing a Django Web Application (https://github.com/yashshah14093/SHOP-PY/tree/master/Shop-py/WebApp). I have added images in the img folder of static files. But When I make a GET Request, I got an error mentioned below. Please help me to resolve this issue. -
Scrapy/Django - PyCharm debugger - can't import model
I have a spider that scrapes websites based on Django model Domain. I created a custom configuration for scrapy to be able to use PyCharm Debugger. The problem is that when I run spider using Debugger, it raises this error: from core.models import Domain ModuleNotFoundError: No module named 'core.models' But when I run it this way: scrapy crawl domain_spider it works correctly. import os import sys from datetime import timedelta import django import scrapy from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor from scrapy.spiders import Spider DJANGO_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(DJANGO_DIR) print(DJANGO_DIR) os.environ['DJANGO_SETTINGS_MODULE'] = 'mspiders.settings' django.setup() from core.models import Domain from django.db.models import Q from django.utils.timezone import now class DomainSpider(Spider): name = 'domain_spider' custom_settings = { 'USER_AGENT': "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36", 'LOG_FILE': 'logs/domain_spider.log', 'CONCURRENT_REQUESTS': 100, 'DOWNLOAD_TIMEOUT': 20, 'DNS_TIMEOUT': 20, 'RETRY_TIMES': 2, 'LOG_LEVEL': 'INFO', } def start_requests(self): The sys.path.append(DJANGO_DIR) line prints this: '/home/milano/PycharmProjects/spiders/mspiders' which is a correct Django project directory This is a configuration: This is very weird since I use such a configuration often without any problems. -
Django model last modification datetime, how to exclude the influence of some fields?
I use DateTimeField with auto_now=True to store last update datetime: updated_at = models.DateTimeField(auto_now=True) I want to update this datetime for all changes in model exclude some fields. Example model: class MyModel(models.Model): field1 = models.IntegerField() field2 = models.IntegerField() updated_at = models.DateTimeField(auto_now=True) So, i need updated_at field to be updated if something changes in the model, but except changes in field2. Is there a solution to do it with auto_now? Or i need to do it manually, for example, by overriding save() method or etc? I will be grateful for any suggestions how to solve it! -
Configure Pycharm Pro for Django
I just got the Pycharm's Pro Student License. I have looked up on the internet on how to configure the settings, however apart from syntax highlighting, nothing much has changed. For example in terminal people just type commands without - python mange.py ..... And the small run button starts the server. None of this work on my pycharm. Can you please tell me how to get those things working. And if I have a previously build django project what setting do I need to change while opening it. -
domain restriction does not doing anything
Hello I have a simple form where I want to save information. I added the domain restriction in my forms but it still saves emails with other email domains. I am new to django maybe it is an easy task, thanks. models.py from django.db import models class WPGroup(models.Model): name=models.CharField(max_length=128,blank=False) number=models.PositiveIntegerField(blank=False) bolum=models.CharField(max_length=128,blank=False) mail=models.EmailField(max_length=128,blank=False) def __str__(self): return self.name forms.py from django import forms from .models import WPGroup class WPGroupForm(forms.ModelForm): class Meta: model=WPGroup fields=['name','number','bolum','mail'] def clean_email(self): email = self.cleaned_data['mail'] if "@itu.edu.tr" not in email: raise forms.ValidationError("You must include @itu.edu.tr") return email views.py class WPGroupView(generic.CreateView): template_name='wp.html' form=WPGroupForm model=WPGroup fields=['name','mail','bolum','number'] success_url='success/' -
535, b'5.7.8 Username and Password not accepted with G Suite and Django
I'm trying to send email from my G Suite account. I have enabled 2FA and generated an app password that I'm using in my django project. My settings.py file looks like this: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = os.getenv("EMAIL_USER") EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = os.getenv("EMAIL_USER") EMAIL_HOST_PASSWORD = os.getenv("EMAIL_PASSWORD") I have set the EMAIL_HOST_PASSWORD as the 16 character generated app password. Why is it still failing? (There is no way to allow "less secure apps" with G Suite if I got 2FA enabled - I'm just redirected to creating an app password, which is what I have done) I just keep getting (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials 29sm2220422ljv.72 - gsmtp') What setting am I missing? -
Django query for the top 5
I have this two model: class State(models.Model): name = models.CharField("State",max_length=255) class Breakdowns(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE,verbose_name="State") date = models.DateField(blank=True,null=True,verbose_name="Date") ... ... ... ... As you can see i can have 1 State with severeal breakdows. How can i show the top 5 state's with more breakdowns ? -
No user link in auth section of Django admin
I am trying to implement a custom user model, but under the auth section of the Django admin website my model is not showing up. I found an answer at the link below to the overall problem, but when trying to implement it myself I still do not see the users in the auth section of the Django admin. No “Users” link in “Auth” section of Django admin site what am I doing wrong here ? models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm CustomUser = get_user_model() class CustomUserAdmin(UserAdmin): form = CustomUserChangeForm add_form = CustomUserCreationForm model = CustomUser list_display = ( "email", "username", ) fieldsets = ( (None, {"fields": ("email", "password")}), ("Permissions", {"fields": ("is_admin", "groups", "user_permissions")}), ) admin.site.register(CustomUser, CustomUserAdmin) forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ("email", "username") class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() fields = ("email", "username") -
Importing scipy stats makes django time out on AWS elastic benastalk
I have a moderately complex api in Elastic Beanstalk. It uses celery and django. It's driving me crazy that just trying to import scipy stats makes django not be able to return anything. I've checked the instance and there is available memory and cpu. I singed out scipy by elimination, as python won't even return an error. I am running version 3.6 of python, scipy version 1.5.2 . I have a rather long list of libraries installed. Even when not using scipy (just importing it) the script will just not return anything. Commenting the import makes everything work fine. I have tried importing the library on a new development with the same characteristics and it seems to work. Any ideas as to what might be causing this behavior? -- Edit -- It looks like adding the full list of requirements makes the new development have the same problem (even though it is just a default django app that does nothing but show an index.html file). So I am adding the list of libraries. I am guessing one of them is having problems with scipy. aiocontextvars==0.2.2 amqp==2.5.2 asgiref==3.2.4 attrs==19.3.0 awscli==1.18.28 awsebcli==3.17.1 bcrypt==3.1.7 billiard==3.6.3.0 blessed==1.17.2 boto3==1.12.16 botocore==1.14.0 botometer==1.5 cached-property==1.5.1 celery==4.4.2 cement==2.8.2 certifi==2020.4.5.1 … -
ERROR: Could not find a version that satisfies the requirement request (from versions: none)
I am trying to install request package on windows 10 terminal using pip install request. But I am getting this error ERROR: Could not find a version that satisfies the requirement request (from versions: none) ERROR: No matching distribution found for request Where I am going wrong -
django.db.utils.IntegrityError: null value in column "state" violates not-null constraint DETAIL:
In my models.py I have state = enum.EnumField(CertificateStatus, verbose_name=_('State')) When I try to submit my Modelform I get the following error. django.db.utils.IntegrityError: null value in column "state" violates not-null constraint DETAIL: Failing row contains (8, 2020-08-24 13:10:23.007867+00, 2020-08-24 13:10:23.007887+00, user/5/certificates/CvCandidat_C00370440_8045152_01_e5xylKe.docx, 1, , 2020-08-24, 5, null, null). -
Generic detail view --userprofile link with post author
I am trying to view post author profile page from blog detail page and for that #views.py class UserProfileView(DetailView): model = Userinfo template_name = "accounts/userinfo.html" def get_context_data(self, *args, **kwargs): context = super(UserProfileView, self).get_context_data(*args,**kwargs) context['author_page'] = get_object_or_404(Userinfo, user=self.kwargs.get('username')) return context and the url has to something like http://127.0.0.1:8000/profile/test2/ path('profile/<str:username>/', UserProfileView.as_view(), name='user_profile'), postdetail page <a href="{% url 'user_profile' username=post.author.username %}">{{ post.author.username }}</a> and model.py class Userinfo(models.Model): user = models.OneToOneField(accountUser, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) bio = models.TextField(max_length=800) def __str__(self): return self.user.username -
matching django url with views using a model slug
my problem is that I can not establish a reverse match, most likely doing something wrong with my url definition (?). Ultimately what I am trying to do is the following: User selects 2 location points which the 'new_pointview' view, saves into a DB. I also define a unique slug which contains location information and save it to the DB via the save() within the model. Then the user should be redirected to a url (pointview view) which uses the slug I created in the previous step i.e /pointview/slug. Here is the code: models.py class Points(models.Model): starting_point_longitude = models.FloatField(null=True) starting_point_latitude = models.FloatField(null=True) ending_point_longitude = models.FloatField(null=True) ending_point_latitude = models.FloatField(null=True) url = models.SlugField(max_length=250, null=True, unique=True, blank=False) def save(self, *args, **kwargs): self.url = 'start_lon-{0}-start_lat-{1}-end_lon-{2}-end_lat-' \ '{3}'.format(self.starting_point_longitude, self.starting_point_latitude, self.ending_point_longitude, self.ending_point_latitude) super(Points, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('pointview', kwargs={'url': self.url}) views.py def pointview(request, url): point = get_object_or_404(Points, url=url) content = {'starting_point_longitude': point.starting_point_longitude, 'starting_point_latitude': point.starting_point_latitude, 'ending_point_longitude': point.ending_point_longitude, 'ending_point_latitude': point.ending_point_latitude} return render(request, 'points.html', {'user_bundle': content}) def new_pointview(request): Points.objects.create( starting_point_longitude=request.POST['starting_point_longitude'], starting_point_latitude=request.POST['starting_point_latitude'], ending_point_longitude=request.POST['ending_point_longitude'], ending_point_latitude=request.POST['ending_point_latitude'], ) points_filtered = Points.objects.filter( starting_point_longitude=request.POST[ 'starting_point_longitude']).filter( starting_point_latitude=request.POST[ 'starting_point_latitude']) unique_url = points_filtered.values()[0]['url'] return redirect('/pointview/{0}/'.format(unique_url)) urls.py urlpatterns = [ path(r'^pointview/(?P<url>[-\w]+)/$', views.pointview, name='pointview'), path('^new_pointview/', views.new_pointview, name='new_pointview'), ] The error: The current path, pointview/start_lon-738949.9146592747-start_lat--153698.8751025315-end_lon-759997.8063993475-end_lat--168467.65638300427/, didn't match any of URL … -
Django admin TeaxtArea 100% width
I've made my CharField view as Text area as foolows: # admin.py class PostAdminForm(forms.ModelForm): text = forms.CharField(widget=forms.Textarea) class Meta: model = Post fields = '__all__' class PostAdmin(admin.ModelAdmin): form = PostAdminForm And it looks like this: admin page So I want to set area's width to 100% - to make it occupy all side from the rigth, how should I to do this? -
How can I show all the images of a model in one page?
I followed This tutorial to set up the model for my gallery page where I'll be showing pictures related to each topic. In the tutorial, the images were shown in a separate page to where the post titles was displayed. However, I want to display all the images , organized by placing them under their respective titles, in one page. How can I do this? Thank you in advance -
Can't link leaflet js file to my html in django
I am new to leaflet and have just created my first mapping app using Django. It is an awesome program but I just wanted to change the style of my map. I am drawing from this amazing resource however I am having trouble linking the js file with the HTML. I have never connected JS to HTML particularly within Django (not sure if it makes a difference). But I am returning 404s 24/Aug/2020 12:19:16] "GET /static/js/leaflet-providers.js HTTP/1.1" 404 1695 I have stored the js file in a folder called static, based on some good practise I read about (please disabuse me of this if it is not good practise!) My relevant chunk of code is as follows: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Anybody</title> <!---leaflet css ---> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/> <!---leaflet JS --> <!-- Make sure you put this AFTER Leaflet's CSS --> <script src="http://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script> <script src="static/js/leaflet-providers.js"/> </script> -
Is there a way I can solve this syntax error?
Am getting SyntaxError: 'return' outside function on my code. I have checked the indentation and it's fine, can someone help me? Here's my code. from django.shortcuts import render from .forms import form from django.core.mail import send_mail from django.http import HttpResponse, HttpResponseRedirect def index(request): return render(request, 'index.html', {}) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['name'] message = form.cleaned_data['name'] sender = form.cleaned_data['sender'] cc_myself = form.cleaned_data['cc_myself'] recipients = ['hillariouskelly@gmail.com'] if cc_myself: recipients.append(sender) send_mail(name, email, message, sender, recipients) return HttpResponseRedirect('/thanks/') -
Django : reference to models in view --> Local variable might be referenced before assigment
I have a small Django-app were I want to manage two stock portfolios. I created two tables (SecuritiesSVR and SecuritiesAHT) with the same structure (based on an abstract model). In the url I added an argument 'ptf' : portfolio/str:ptf/change_position Now I want to access these two tables via a view as underneath: @login_required def change_position(request, ptf, symbol): if ptf == 'aht': Securities = SecuritiesAHT if ptf == 'svr': Securities = SecuritiesSVR security = Securities.objects.get(pk=symbol) ... In PyCharm I get a warning on my variable Securities : "Local variable might be referenced before assigment'. However, the view seems to work correctly. Does anyone know why I get this warning? -
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) in Python Django
Traceback (most recent call last): File "C:\users\xx.virtualenvs\xx-SFDz4XJ_\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\users...virtualenvs\xx-SFDz4XJ_\lib\site-packages\django\core\handlers\base.py", line 115, in ge t_response response = self.process_exception_by_middleware(e, request) File "C:\Users\xx.virtualenvs\xx-SFDz4XJ\lib\site-packages\django\core\handlers\base.py", line 113, in ge t_response response = wrapped_callback(request, callback_args, *callback_kwargs) File "c:\users\xx\appdata\local\programs\python\python37-32\Lib\contextlib.py", line 74, in inner return func(*args, **kwds) File "C:\Users\xx.virtualenvs\xx-SFDz4XJ\lib\site-packages\django\views\decorators\csrf.py", line 54, in w rapped_view return view_func(*args, **kwargs) File "D:\xx\ProjectSourceCode\xx\xx\xx\views.py", line 1942, in post_product post_response = requests.post(post_url, json=data_post, headers=headers).json() File "C:\Users\xx.virtualenvs\xx-SFDz4XJ_\lib\site-packages\requests\models.py", line 898, in json return complexjson.loads(self.text, **kwargs) File "c:\users\xx\appdata\local\programs\python\python37-32\Lib\json_init_.py", line 348, in loads return _default_decoder.decode(s) File "c:\users\xx\appdata\local\programs\python\python37-32\Lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "c:\users\xx\appdata\local\programs\python\python37-32\Lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Note: it's work fine in Window server but it's got this error in Linux server. -
How to create another user (students and teachers) table in django
I'm using django and have some confusion right now. I want to build something where teachers table will be in a onetomany relationship with students table. But I could not create another student table. Any advice or resource,please? -
Getting error converting data type nvarchar to numeric while saving django form to mssql database
I'm using django-pyodbc-azure with mssql and i have set some fields as foreign key in my models.py: class Production(models.Model): date = models.CharField(max_length=10, null=True) dateGr = models.DateField(auto_now=False, auto_now_add=False, null=True) comName = models.CharField(max_length=100, null=True) comId = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) prodName = models.CharField(max_length=100, null=True) prodId = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) gradeId = models.ForeignKey(ProductGrade, on_delete=models.CASCADE, null=True) gradeName = models.CharField(max_length=100, null=True) gradeType = models.CharField(max_length=3, null=True) gradeTypeId = models.ForeignKey(GradeType, on_delete=models.CASCADE, null=True) qty = models.FloatField(null=True) cap = models.FloatField(null=True) designCap = models.FloatField(null=True) plan = models.FloatField(null=True) unitId = models.ForeignKey(QtyUnit, on_delete=models.CASCADE, null=True) unit = models.CharField(max_length=20, null=True) And i have written my forms.py like this: class CreateProduction(forms.ModelForm): class Meta: model = Production fields = ['date', 'comId', 'prodId', 'gradeId', 'gradeTypeId', 'unitId', 'qty'] widgets = { 'date': forms.TextInput(attrs={'class': 'form-control', 'name': 'tdate', 'id': 'input-tdate'}), 'comId': forms.Select(attrs={'class': 'form-control'}), 'prodId': forms.Select(attrs={'class': "form-control"}), 'gradeId': forms.Select(attrs={'class': 'form-control'}), 'gradeTypeId': forms.Select(attrs={'class': 'form-control'}), 'unitId': forms.Select(attrs={'class': 'form-control'}), 'qty': forms.NumberInput(attrs={'class': 'form-control', 'id': 'qty', 'type': 'number', 'value': '0'}), } def __init__(self, user, comId, *args, **kwargs): super(CreateProduction, self).__init__(*args, **kwargs) self.fields['comId'].queryset = Company.objects.filter(userId=user) self.fields['prodId'].queryset = Product.objects.filter(comId=comId) products = Product.objects.filter(comId=comId) self.fields['gradeId'].queryset = ProductGrade.objects.filter(prodId__in=products) The function that handles saving my form's data to database is as following: @login_required(login_url='login') @allowed_users(allowed_roles=['editor']) def create_production(request): print(request) if request.method == 'POST': comId = Company.objects.values_list('id', flat=True).get(userId=request.user) form = CreateProduction(request.user, comId, request.POST) if form.is_valid(): production = … -
update vue-chartjs yaxis max value
I am working on a project where i am implementing some charts. I need the Y-axis max value to change everytime the user changes the filters given. I Import an existing barchart from the vue-chartjs library. In the code there is a javascript file that has some defaults already: import { Bar } from 'vue-chartjs' import { hexToRGB } from "./utils"; import reactiveChartMixin from "./mixins/reactiveChart"; let defaultOptions = { tooltipFillColor: "rgba(0,0,0,0.5)", tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", tooltipFontSize: 14, tooltipFontStyle: "normal", tooltipFontColor: "#fff", tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", tooltipTitleFontSize: 14, tooltipTitleFontStyle: "bold", tooltipTitleFontColor: "#fff", tooltipYPadding: 6, tooltipXPadding: 6, tooltipCaretSize: 8, tooltipCornerRadius: 6, tooltipXOffset: 10, }, legend: { display: false }, scales: { yAxes: [{ ticks: { fontColor: "#9f9f9f", fontStyle: "bold", beginAtZero: true, stepSize: 10, padding: 10, display: true, min: 0, }, gridLines: { zeroLineColor: "transparent", display: false, drawBorder: false, color: '#9f9f9f', } }], xAxes: [{ barPercentage: 1, gridLines: { zeroLineColor: "white", display: false, drawBorder: false, color: 'transparent', }, ticks: { padding: 20, fontColor: "#9f9f9f", fontStyle: "bold" } }], legend: { display: true } } }; export default { name: 'BarChart', extends: Bar, mixins: [reactiveChartMixin], props: { labels: { type: [Object, Array], description: 'Chart labels. This is overridden when `data` … -
Creating a linked hashtag in markdown
I'm currently trying to parse markdown in django/python and linkify hashtags. There are some simple solutions to this: for tag in re.findall(r"(#[\d\w\.]+)", markdown): text_tag = tag.replace('#', '') markdown = markdown.replace( tag, f"[{tag}](/blog/?q=%23{text_tag})") This works well enough, but converts everything with a # into a link. Eg: https://example.com/xyz/#section-on-page gets linkified. It also gets linkified if it is currently inside of a link itself. Internal links are also broken as Link get linkified. Here's a comprehensive case: #hello This is an #example of some text with #hash-tags - http://www.example.com/#not-hashtag but dont want the link #hello #goodbye #summer #helloagain #goodbye This is #cool, yes it is #radaf! I like this #tool. [Link](#not-a-hashtag) [Link](https://example/#also-not) <a href="#this-neither">Hai</a> Thanks