Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i don't understand the error in these fie
i have facing these issue while creating template in django as i am creating template while adding template attribute in setting.py its showing the error syntax is invalid TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [[os.path.join(BASE_DIR,'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', ], }, }, ] return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "F:\myweb\myweb\settings.py", line 59 'APP_DIRS': True, ^ SyntaxError: invalid syntax MPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [[os.path.join(BASE_DIR ,'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', ], }, }, ] WSGI_APPLICATION = 'myweb.wsgi.application' i am creating a html file under ajango template but when i am trying to run it o browser it shows the error file doesnot exists from django.apps import AppConfig class NewappConfig(AppConfig): name = 'newapp' its have to show hello there!!! on browser -
A function present in views.py file need to access the images stored in my pc
I need to include some image processing code in django. For that I want to access images stored in my pc (or in static folder in django ) through function in views.py. How can I do that? -
How to make Django views require a user login?
I have a Django project with a login screen; when I enter my username and password I get directed to the home page. This works fine! But nothing is secure, I can just go to the view at /allstudyplans without logging in and see all the information there. My Question is how do I make it so it's not possible to go /allstudyplans without logging in first? Form User = get_user_model() class UserLoginForm(forms.Form): username = forms.CharField(label='', widget=forms.TextInput( attrs={ 'class': 'form-control', 'autofocus': '', 'placeholder': 'Användarnamn', } ), ) password = forms.CharField(label='', widget=forms.PasswordInput( attrs={ 'class': 'form-control mt-1', 'placeholder': 'Lösenord', } ), ) # https://docs.djangoproject.com/en/2.1/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other def clean(self): cleaned_data = super().clean() username = cleaned_data.get('username') password = cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError( 'Oh! I can\'t find that user - create user first!') elif not user.check_password(password): raise forms.ValidationError( 'Oh! That password is incorrect - try again!') elif not user.is_active: raise forms.ValidationError( 'Oh! That user is not active in the database!') Views def home(request): next = (request.GET.get('next')) form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) if next: return redirect(next) return redirect('/') context = { 'form': form, } … -
How to set a model boolean field based on conditional logic of other field values
I have a Template model with a 1:many FK with a Post model: class Template(model.Models): #foo class Post(model.Models): template = models.ForeignKey( Template, null=True, on_delete=models.SET_NULL) I want to create an 'automatic' boolean field that flags if there is one or more posts using the template (if True I will lock the template for editing). What's the best way to do this? Is it via a @property decorator on the Template model??: @property def can_edit(self): if self.object.post_set.all() >= 1: self._can_edit = True return self._can_edit else: self._can_edit = False return self._can_edit Then I would call this via {{ template.can_edit }} to display the flag status and {% if template.can_edit() %} to run conditional logic, but this does not work. -
Take the data of one table and make the field for another table
Models.py class Designation(models.Model): Name = models.CharField(max_length=50) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return self.Name class Meta: db_table = 'desingnation' all the data should create as field to another table -
Watching for file changes with StatReloader Exception in thread django-main-thread:
**Don't know what the problem is. I am not able to run any of my Django servers. Every time gets the same error. And don't have any idea about this. Tried reinstalling windows, python and all. But still gets same error. ** Don't know what the problem is. I am not able to run any of my Django servers. Every time gets the same error. And don't have any idea about this. Tried reinstalling windows, python and all. But still gets same error. C:\Users\JamesBond\Desktop\ONLINE WEBSITES\vishwatradelink_>manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\JamesBond\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line … -
Problem with Django foreign key field with to_field attribute
I have my model of User object which is related to Group object (example). So user has something like: group_name = models.ForeignKey(Group, to_field="group_name", ...) (of course the group_name is defined as unique as it's not a primary key in Group object) But when I'm trying to change the group_name value for some Group object (regardless it's via Admin interface or within the code by updating the selected object) it raises the Integrity error: FOREIGN KEY constraint failed I know there is a mandatory parameter on_delete for the foreign key filed but I've tried all potential pre-defined values (models.SET_DEFAULT, models.CASCADE, etc.) but without any change. It seems to me I need something what to do on_update, but that's not possible attribute ;-) Thanks -
Side bar menu should load based on role based login django
Based on the Designation, Menu should load while the Employee login to the application. Its like a role based login or Access control permision -
django ORM problem - Annotate and aggregate return inconsistent values
I found a setup where aggregate() and annotate() do NOT return the same values... I am really confused. I have the following models: class Invoice(models.Model): pass class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, related_name="items") amount = models.PositiveIntegerField(null=False, blank=False, default=1) price = models.DecimalField(max_digits=10, decimal_places=2, null=False, blank=False, default=0) begin = models.DateField(null=True, blank=True) When I want to get the total revenue over a timespan, I have the following query: revenue = Invoice.objects.annotate( first_date=Min('items__begin')).filter( first_date__range=[start_date, end_date]).aggregate( revenue=Sum(F('items__amount') * F('items__price'), output_field=FloatField()))['revenue'] I tried to do the same with annotate() just to verify the results: revenue_list = Invoice.objects.annotate( first_date=Min('items__begin')).filter( first_date__range=[start_date, end_date]).annotate( revenue=Sum(F('items__amount') * F('items__price'), output_field=FloatField())) When I now loop over the elements and manually sum up revenue I get a different value than revenue. Any ideas? Unfortunately after an aggregation you cannot check the raw query anymore... Thanks! -
Generate PDF in Django Python with customize header/footer and different header/footer in different pages in a single pdf
I want to generate pdf using django python. Pdf will have customize headers and footers and different headers and footers on different pages in a single pdf file. I have already tried WKHTML but it doesn't give option of different headers and footers in a single file. WKHTML Library Expecting: Different headers and footers on different pages in a single pdf file. -
How to retrive data from related table in djnago
Hey I want retrieve all staff information with there respective Operating Hours please help me, Here is my models class Staff(models.Model): vendor = models.ForeignKey(Vendor,on_delete=models.DO_NOTHING,blank = True) name = models.CharField(max_length=100) last_name = models.CharField(max_length = 100) gender = models.IntegerField(choices=GENDER_TYPE, default=0) class OperatingHours_staff(models.Model): staff = models.ForeignKey(Staff,related_name='days',on_delete = models.CASCADE) day = models.IntegerField(choices = constants.DAYS) start_time = models.TimeField() end_time = models.TimeField() Thanks in Advance -
Where does ArrayField create SimpleArrayField in Django?
I want to review the code and maybe override it for my needs, where SimpleArrayField is created for ArrayField in Django. Unfortunately I can't find or don't understand where it happens. I've searched through ArrayField and only place where SimpleArrayField is mentioned is this method. Since method returns super().formfield(...'form_class': SimpleArrayField...), I've searched for formfield() in inherited classes (CheckFieldDefaultMixin, Field), but found nothing. -
DRF loading binary files sending from React app
I made a standard API for downloading files to AWS S3. Using the standard DRF interface, the files are loaded correctly into the repository. models.py class Documents(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) upload = models.FileField(storage=PrivateMediaStorage()) filename = models.CharField(_('documents name'), max_length=64) datafile = models.FileField() created = models.DateTimeField(auto_now_add=True) type = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True) views.py class DocumentsListView(AwsUrlMixin, viewsets.ViewSetMixin, generics.ListCreateAPIView): queryset = Documents.objects.all() serializer_class = DocumentsSerializer permission_classes = (IsAuthenticated, LifeLinePermissions) pagination_class = None def perform_create(self, serializer): serializer.save(author=self.request.user) Problems begin when the download is done through the user interface and the file is transferred using React. The file comes in binary form, and django does not accept this format by saying datafile: ["No file was submitted."] An error occurs in the django console HTTP POST /api/v1/files/ 400 [0.02, 127.0.0.1:33916] In the browser debugger -
How to implement upload image via url in django
Basically I am creating a website where you can upload images of different websites using url. How to implement it. How to validate if it is an image and how to fetch it and store in your database -
how to remove or delete django project
screenshot image1 I use visual studio code and create a django project(python-training).Q1:I can't use 'open with live server' to see html file, instead the file in python-training directory. what I can do to remove or delete django project? Q2:why the python-training directory don't have the following files: setting.py, manage.py thank you all for give me a hand screenshot image2 screenshot image3 -
Memcached reflecting changes automatically from the built in User model, how?
I am using memcached in my code to represent some lists in web. I am doing something like this, from django.core.cache import cache #inside view cache_key='somekey' cache_time=sometime data=cache.get(cache_key) if not data: #some code cache.set(cache_key,data,cache_time) return render(...) It is working perfectly. Cache is serving the pages. But here I am observing that, any changes in the database in the build in User model is getting reflected in the cache automatically. how is this happening? And my 2nd question is, what is the best way to reflect the database changes in the memcached. I already tried to maintain, flags in the database using a trigger. It is working, but it is not possible to maintain different flags for every cache in the db as some urls has in them. Any help will be appreciated.. -
Any Suggestions please
I am building a website for image hosting. People can upload via url or images directly from their device. Trying to implement it on python / Django but not getting the proper tutorials. Any suggestions? Should I use aws s3 for storage and ec2 for server. Any suggestions? I am lost. -
Django: Request data is missing while calling view from view
I am calling view from another view in for loop. First time, view is processed properly but next time request object is empty. for index, component in enumerate(components_list): AggregateData.as_view()(request._request, nquery=index) Here for second iteration request object is empty (request is <QueryDict: {}>). Not sure where I am going wrong. -
Django defining custom routing rules
I come from a TypeScript/Express.js background when it comes to developing APIs, and normally we have a custom AuthRouter that we structure similar to below (implementation scrubbed for client security). We do our auth by taking a Bearer token and sending it to an external API for validation: // app.ts /* Express app setup */ app.use(AuthRouter); /* Other modules that define our other app routes/services */ // AuthRouter.ts router = express.Router() router.all(config.API_BASE + '*', async (req, res, next) => { validate(req.headers.authorization) next(); }); Is there a similar way to achieve the same routing flow in Django? I've already looked into defining a custom Authentication Backend, but I'm afraid it won't play nice since it appears to be coupled to a "User" which isn't the goal, so i can't satisfy the minimum requirements. Is leaving the get_user function empty a valid approach? Ideally, I'm looking for whatever can simulate that next() callback that Express provides. If I have to setup the callback functionality myself, I will, although I think that could get pretty hairy. Any tips would be appreicated!! -
How to solve multiple http request in django googlesearch?
Actually I know the reason why this error is coming but dont know how to solve it. This problem came because of captchas which comes when anything is searched in the google.com. How to remove it .Or there is any alternative to do this. from googlesearch import search for i in search("query",tld='co.in',lang='en',num=10,stop=1,pause=2): print (i) I have already tried by reducing the resting period of the google search. -
Celery & channels conflict
I'm using the latest celery and channels.But I found that when I use channels,My celery can't receive task submit by djano.When I close the channels in django, Celery works well.Dose channels and celery has something conflict? My channels config is: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [("redis://:*@127.0.0.1:6379/4")], }, }, } My celery config is: CELERY_ACCEPT_CONTENT = ['application/json',] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' BROKER_URL = 'redis://:*@127.0.0.1:6379/3' CELERY_RESULT_BACKEND = 'redis://:*@127.0.0.1:6379/2' And I just use python manage.py runserver to start django and channels -
Multiple subdomains with django
I'm trying to run two applications on a webserver with Django + Apache at signal.server.com and noise.server.com. Currently both URLs point to singal.server.com I've been changing options around to no avail. Here is my virtual host for the server.com which works fine WSGIPythonPath /var/www/html/d_signal WSGISocketPrefix run/wsgi <VirtualHost *:80> ServerAdmin hello@mail.server.com ServerName www.server.com DocumentRoot /var/www/html <Directory /var/www/html/> Options Indexes FollowSymLinks AllowOverride All </Directory> ErrorLog /var/log/httpd/server.error.log CustomLog /var/log/httpd/access.log combined <IfModule mod_dir.c> DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm </IfModule> </VirtualHost> virtual config for singal.server.com <VirtualHost *:80> ServerAdmin hello@server.com ServerName signal.server.com ServerAlias signal.server.com DocumentRoot /var/www/html/d_signal/d_signal WSGIScriptAlias / /var/www/html/d_signal/d_signal/wsgi.py WSGIDaemonProcess signal.server.com python-home=/var/www/html/d_signal/signal_env socket-user=apache WSGIProcessGroup signal.server.com Alias /static /var/www/html/d_signal/static <Directory /var/www/html/d_signal/sig/templates/sig/static> #Require all granted </Directory> <Directory /var/www/html/d_signal/d_signal> AllowOverride all #Require all granted Options Indexes FollowSymlinks <Files wsgi.py> #Require all granted </Files> </Directory> </VirtualHost> And the virtual config for noise.server.com <VirtualHost *:80> ServerAdmin hello@server.com ServerName noise.server.com ServerAlias noise.server.com DocumentRoot /var/www/html/d_signal/noise WSGIScriptAlias / /var/www/html/d_signal/d_signal/wsgi_noise.py WSGIDaemonProcess noise.server.com python-home=/var/www/html/d_signal/noise_env socket-user=apache WSGIProcessGroup noise.server.com Alias /static /var/www/html/d_signal/static <Directory /var/www/html/d_signal/sig/templates/sig/static> #Require all granted </Directory> <Directory /var/www/html/d_signal/noise> AllowOverride all #Require all granted Options Indexes FollowSymlinks <Files wsgi_noise.py> #Require all granted </Files> </Directory> </VirtualHost> If I visit http://noise.server.com/noise/ then I get to the app I want to see. What am I missing here? -
How to get refresh token value within python / django social auth?
Strava is moving from forever tokens to refresh tokens. Part of my app portfolio is a website powered by django that uses python social auth and some django social auth bits to authorize users against their strava credentials. I'm able to get it working fine in the website but can't figure out how to get access to the refresh token values. I need the refresh token values given I have batch processes that use them to connect to strava and sync activities, etc. I expected them to be in the extra data field in the django db but alas only the token, the type and the auth_time are present. So far I've upgraded the following libraries to get this far: social_auth_core and social-auth-app-django. Any ideas? Perhaps I also need to upgrade python-social-auth? I'm assuming there is a oauth2 module that receives the direct with the extra data as url parameters. Just don't know what method that is... Thanks in advance for any suggestions. best, mike -
Using the Django admin site for specific instances of a model
I am working on my first Django app, and was thinking of using a rather abstract database schema, like this: class ListCategories(models.Model): name = models.TextField(max_length=200) type = models.TextField(max_length=200) class ListItems(models.Model): category = models.ForeignKey('ListCategories', on_delete=models.CASCADE) item = models.TextField(max_length=200) sorstorder = models.IntegerField() class ObjectType(models.Model): name = models.TextField(max_length=200) class Object(models.Model): type = models.ForeignKey('ObjectType', on_delete=models.CASCADE) name = models.TextField(max_length=200) class ObjectTypeProperties(models.Model): name = models.TextField(max_length=200) object_type = models.ForeignKey('ObjectType', on_delete=models.CASCADE) list_category = models.ForeignKey('ListCategories', null=True, on_delete=models.CASCADE) class ObjectProperties(models.Model): object = models.ForeignKey('Object', on_delete=models.CASCADE) property = models.ForeignKey('ObjectTypeProperties', on_delete=models.CASCADE) list_item = models.ForeignKey('ListItems', on_delete=models.CASCADE) result = models.TextField(max_length=200) class HistoricalNumericalData(models.Model): object = models.ForeignKey('Object', on_delete=models.CASCADE) object_property = models.ForeignKey('ObjectProperties', on_delete=models.CASCADE) value = models.FloatField() class Image(models.Model): object = models.OneToOneField('Object',on_delete=models.CASCADE) image = models.ImageField() def image_tag(self): return mark_safe('<img src="{}"/>'.format(self.image.url)) image_tag.short_description = 'Image' This is very flexible on the DB, as you can add object types and object properties by simply adding lines to the DB. However, I would like to use the admin interface to add new Objects to the database, and this is where this schema is tricky to use. The form would need to be different for each object type, however, as they would have not the same properties. Is there a way to register models to use with the admin site that behave differently according … -
Django - Data query based on user permissions or user group name
I'm new to Python and started a project where I have a list of Customers that are distributed across different Regions of the world. System users should only have access to users in their own region I added custom permissions for the class Customer. I'm trying to find a way to list all the Customers in one or more regions (for example: latam, emea, us, ...) based on Authentication group name or user permission. Is that possible?? views.py class CustomerListView(PermissionRequiredMixin, LoginRequiredMixin, generic.ListView): model = Customer context_object_name = 'customers' template_name = 'customers/customer.html' login_url = '/' permission_required = 'customer.view_customer' permission_denied_message = 'User has no permission to perform this action.' model.py class Region(models.Model): region_id = models.AutoField(primary_key=True) region_name = models.CharField(max_length=12, unique=True) def __str__(self): return self.region_name class Customer(models.Model): class Meta: permissions = ( ("latam_view", "Can acceess LATAM data"), ("us_view", "Can acceess US data"), ("emea_view", "Can acceess EMEA data"), ) customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=15, null=False, blank=False, unique=True) primary_contact_name = models.CharField(max_length=24, null=False, blank=False) primary_contact_position = models.CharField(max_length=25, null=False, blank=False) primary_contact_department = models.CharField(max_length=15, null=False, blank=False) primary_contact_phone = models.CharField(max_length=17, null=False, blank=False) primary_contact_email = models.EmailField(max_length=30, null=False, blank=False) customer_region = models.ForeignKey(Region, on_delete=models.PROTECT, null=False, blank=False) auth_group = models.ForeignKey(Group, on_delete=models.PROTECT, null=False, blank=False) def __str__(self): return self.customer_name Thank you