Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CAN NOT import rest framekwork in Django
I am very very NEWBIE in django. But i've faced the problem, that i couldn't find here. I have installed virtualenv; IN virtualeenv i've installed django and rest_framework. However, i cannot import rest to the project. when i install again: Requirement already satisfied: djangorestframework in src\myvenv\lib\site-packages (3.11.0), etc. My projects and virualenvs in disk 'D' if it's somehow affects. I have latest django and python version. Thank you -
how to create unique_together index using Uniqueconstraints function in django?
official document says: UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future. here is my code class Meta: constraints = [models.UniqueConstraint(fields=['token','obj'], name='hello')] when i migrate it creates a migrations with message '- Create constraint create_like on model helloWorld'. but it is not creating an index on database. -
How can I add if statement to a deleteview? CBV django
Hey I want to add if statement and according to it decide if to delete the object or not. I could not find it online. In general how can I add if statements to any CBV including Update for example.. -
Django REST Cache Invalidation
I have a Django project and API view implemented with Rest framework, i'm caching it using the @cache_page decorator but i need to implement a cache invalidation and im not finding how to do that, do i need a custom decorator? The problem: The view check the access of the API KEY and it caches it for previuos access check, but if the user changes the API KEY before the caches expires the view will return an OK status of the key that doesnt exist anymore -
Annotate Queryset with Related Model fields
I have following Schema in Django with PostgreSQL. Class Person (models.Model): name = models.CharField(max_length=255) email= models.CharField(max_legth = 255) created_at = models.DateTimeField() Class PersonTask(models.Model): title = models.TextField() created_at = models.DateTimeField() Class PersonHistory(models.Model): note = models.TextField() created_at = models.DateTimeField() Now I need to query the DB like all values of Person with latest PersonTask__title and latest PersonHistory__note Eg: <Queryset: [{name: "abc" ,email:"abc@gmail.com",created_at :"2019-01-02", Task_Title:"This is my latest tasktitle" , HistoryNote : "This is my latest history note"}, {name: "abcd" ,email:"abcd@gmail.com",created_at :"2019-03-02", Task_Title:"This is my latest tasktitle for abcd" , HistoryNote : "This is my latest history note for abcd"}]> But, I could max get is either id of Latest Task and Latest History by Person.objects.filter(customer_id= 1).annotate( max_task = Max('persontask')).annotate(max_note = Max('personhistory')).order_by('-id') Or a random task or note texts using below query Person.objects.filter(customer_id= 1).annotate( max_task = Max('persontask__title')).annotate(max_note = Max('personhistory__note')).order_by('-id') How this can be tackled?? -
Buffer dtype mismatch, expected 'SIZE-t' but got 'long long'
I developed 3 ML models in spyder, they are Linear Regression, Polynomial Regression and Random Forest Regression. In sypder all pf them worked well. However when I deployed on Django for creating a webapp, Random Forest was raising " ValueError: Buffer type mismatch, expected 'SIZE_t' but got 'long long' ". (I tried removing randomforest and other two models worked well). Check this out first:- ValueError Image of CMD Model Developed in Sypder """****************** Import Lib ******************""" import numpy as np import pandas as pd import seaborn as sns from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score """****************** Loading dataset ******************""" boston = load_boston() dataset = pd.DataFrame(boston.data, columns=boston.feature_names) dataset['target'] = boston.target """****************** Data Preprocessing ******************""" """ Data Analysis """ # Check Null dataset.isnull().sum() # Calculate X and y X = dataset.iloc[:,:-1].values y = dataset.iloc[:,-1].values.reshape(-1,1) # train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=25) """ Visualizing Data """ corr = dataset.corr() sns.heatmap(corr, annot=True, cmap='Blues') sns.pairplot(dataset) """****************** Regression Models ******************""" """ Linear Regression """ from sklearn.linear_model import LinearRegression regressor_linear = LinearRegression() regressor_linear.fit(X_train, y_train) cv_linear = cross_val_score(estimator = regressor_linear, X=X_train, y=y_train, cv=10) """ Polynomial Regression """ from sklearn.preprocessing import PolynomialFeatures poly_reg = PolynomialFeatures(degree = 2) X_poly = poly_reg.fit_transform(X_train) … -
How do I specify DRF oauth required_scopes in function based api_view?
I'm trying to make my function based rest framework views which use the @api_view decorator with the Django OAuth Rest Framework Toolkit, where I'm using TokenHasScope as the permission_class. However, this needs a mandatory attribute called required_scopes but I'm not sure how I can get this specified in a function based views? -
Django: How to save predefined values in modelForm
Good evening, is it possible to change the ModelForm inside my forms.py, so that already known values are saved inside the database? For example: models.py: class Customer(models.Model): name = models.CharField(max_length=255) class Project(models.Model): customer = models.ForeignKey(Customer, null=False, on_delete=models.CASCADE) name = models.CharField(max_length=255) class Entry(models.Model): user = ...request.user.id?... customer = models.ForeignKey(Customer, null=False, on_delete=models.CASCADE) project= models.ForeignKey(Project, null=False, on_delete=models.CASCADE) name = models.CharField(max_length=255) forms.py: class EntryForm(ModelForm): class Meta: model = Entry fields = '__all__' def __init__(self, *args, pk, **kwargs): super().__init__(*args, **kwargs) self.fields['project'].queryset = Project.objects.filter(customer_id=pk) When entering the knew site, I already know about the only possible Customer (pk)! I don't want to place a choicefield inside my knew site, but the customer should be saved inside my database nonetheless! Same goes for the active user (request.user), respectively the id (request.user.id). Can this data be passed into the modelForm as well? Did someone else also had this problem and might know the solution? What do I have to change inside my modelForm to make it work? Thanks for all your efforts and a happy weekend to all of you! -
Running unix shell command from django app hpsted on aws and using apache2 web server
I am using os module for running shell command in django code . It is working fine on local but when running on the apache2 server it is not running os.system(commandDict[i]) on local it is giving status code 0 but on production server it is giving status code 1 can any one suggest alternative or what is going wrong in this . Thanks in advance -
Using a key from a for loop in django
I have an array of arrays that I am trying to put into a table. It's something that works easily in PHP but I can't seem to figure out how to do it in Django. I want to do something like this: {% for o in test %} <tr> <td>{{ test.row{{o}}.test1 }}</td> <td>{{ test.row{{o}}.test2 }}</td> <td>{{ test.row{{o}}.test3 }}</td> </tr> {% endfor %} -
How to run multiple instances of a Django app?
This question doesn't involve any code. I just want to know a way to run multiple instances of a django app and if it is really possible in the first place. I make django apps and host them on Apache. With the apps, I noticed a conflict between multiple users accessing the web app. Let us assume it is a web scraping app. If one user visits the app and run the scraper, the other user accessing the site from a different location doesn't seem to be able to visit the app or run the scraper unless the scraping that the first user started finishes. Is it really possibe to make it independent for all different users accessing the app? Please suggest! Thanks -
django tinymce display issue
I installed tinymce in my django admin in order to beh able to insert code/videos etc in my questions on my quiz-app. But, when I go to display the questions, it appears in code, like if in my tinymce tool I write "c", in the question displayed it will be as follow in the pic: quiz/admins.py from django.contrib import admin from .models import Questions from tinymce.widgets import TinyMCE from django.db import models # Register your models here. class QuestionsAdmin(admin.ModelAdmin): fields = [ 'question', 'optiona', 'optionb', ] formfield_overrides = { models.TextField: {'widget': TinyMCE()}, } admin.site.register(Questions, QuestionsAdmin) quiz/models.py from django.db import models from django.conf import settings # Create your models here. class Questions(models.Model): CAT_CHOICES = ( ('datascience', 'DataScience'), ('productowner', 'ProductOwner'), ('businessanalyst', 'BusinessAnalyst'), #('sports','Sports'), #('movies','Movies'), #('maths','Maths'), #('generalknowledge','GeneralKnowledge'), ) question = models.TextField(max_length = 850) optiona = models.TextField(max_length = 800) optionb = models.TextField(max_length = 800) optionc = models.TextField(max_length = 800) optiond = models.TextField(max_length = 800) answer = models.TextField(max_length = 850) catagory = models.TextField(max_length=20, choices = CAT_CHOICES) class Meta: ordering = ('-catagory',) def __str__(self): return self.question piattaforma/settings.py TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen … -
Reverse for '____' with no arguments not found?
my project error is: NoReverseMatch at / Reverse for 'post_new' with no arguments not found. 1 pattern(s) tried: ['$post/new/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'post_new' with no arguments not found. 1 pattern(s) tried: ['$post/new/$'] Exception Location: k:\ProgramData\Anaconda3\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 673 Python Executable: k:\ProgramData\Anaconda3\python.exe Python Version: 3.7.4 in base.html : 22 <ul class="nav navbar-nav"> 23 <li><a class="navbar-brand bigbrand" href="{% url 'blog:post_list' %}">My Blog</a></li> 24 <li><a class="navbar-link" href="#">About</a></li> 25 <li><a class="navbar-link" href="http:www.google.com">Google</a></li> 26 <li><a class="navbar-link" href="http:www.github.com">Github</a></li> 27 </ul> 28 <ul class="nav navbar-nav navbar-right"> 29 {% if user.is_authenticated %} 30 <li> 31 <a href="{% url 'blog:post_new' %}">New Post</a> 32 </li> 33 <li> 34 <a href="{% url 'blog:post_draft_list' %}">Draft</a> 35 </li> 36 <li> 37 <a href="{% url 'blog:logout' %}">Logout</a> 38 </li> 39 <li> 40 <a>Welcome {{ user.username }}</a> 41 </li>``` -
IntelliJ profiling Django application
I am developing a Django application inside IntelliJ. Now, I would like to profile it. To see, if some code is run more than it should if some queries are slow,... All I can find is : That exist debug tool that shows DB profile Link Python profiler (like vmprof): I did install vmprof and I run it. But my problem is, that all code inside all libraries is showed,... I can't find my code inside.. is there a way to configure to show only my code? -
Email sent to wrong account
Ive built an contact form which sends an email. I'm just having a bit of trouble in relation to the account its being sent to. I want the email to be sent from "servwishes@gmail.com" to the "Contact_Email". Right now the email is going from "Contact_Email" to "servwishes@gmail.com". my views.py looks like this: def contact(request): Contact_Form = ContactForm if request.method == 'POST': form = Contact_Form(data=request.POST) if form.is_valid(): contact_name = request.POST.get('contact_name') contact_email = request.POST.get('contact_email') contact_content = request.POST.get('content') template = get_template('users/contact_form.txt') context = { 'contact_name' : contact_name, 'contact_email' : contact_email, 'contact_content' : contact_content, } content = template.render(context) email = EmailMessage( "New contact form email", content, "Creative web" + '', ['servwishes@gmail.com'], headers = { 'Reply To': contact_email } ) email.send() return render(request, 'users/contact.html', {'form':Contact_Form }) And my setting.py looks like: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'servwishes@gmail.com' EMAIL_HOST_PASSWORD = '*******' EMAIL_PORT = 587 EMAIL_USE_TLS = True -
Django how to capture user data
I currently have a 3 x 3 grid of images, displaying a total of 9 images. The sourced images from 3 different folders(representing 3 different categories). Code for this is in the file random_image.py template to display the images is in pickfeel.html The interface looks like this: I want the user to click on an image and press the 'Next' button. When the 'Next' button is pressed it will record the following data: username Category of selected image What should I do implement this? P.S: I'm inexperienced with Django and any help would be greatly appreciated random_Image.py @register.simple_tag def random_images_category1(count=3): valid_extensions = ('.jpg', '.jpeg', '.png', '.gif') rand_dir = '/static/app_pickfeel/images/normal/' path = '/app_pickfeel/static/app_pickfeel/images/normal/' files = [f for f in os.listdir(settings.BASE_DIR + path) if f[f.rfind("."):] in valid_extensions] print(random.sample(files, count)) return [rand_dir + filename for filename in random.sample(files, count)] @register.simple_tag def random_images_category2(count=9): valid_extensions = ('.jpg', '.jpeg', '.png', '.gif') rand_dir = '/static/app_pickfeel/images/mania/' path = '/app_pickfeel/static/app_pickfeel/images/mania/' files = [f for f in os.listdir(settings.BASE_DIR + path) if f[f.rfind("."):] in valid_extensions] print(random.sample(files, count)) return [rand_dir + filename for filename in random.sample(files, count)] @register.simple_tag def random_images_category3(count=9): valid_extensions = ('.jpg', '.jpeg', '.png', '.gif') rand_dir = '/static/app_pickfeel/images/depression/' path = '/app_pickfeel/static/app_pickfeel/images/depression/' files = [f for f in os.listdir(settings.BASE_DIR + path) if … -
badly formed hexadecimal UUID string in django?
I have a Django version 3.0.5. I have a UUID uuid.uuid4 as a primary key and migrate to tables the in Mysql engine. after migrate I have import the data which present in the SQL lite database. now I have import all the data to Mysql and logged in Django admin I get the error like this badly formed hexadecimal UUID string mymodel.py # # Create your models here. class ChallansModal(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False, unique=True) code = models.CharField(max_length=255,verbose_name='Codes') Date = models.DateField(verbose_name='Date') def __unicode__(self): return self.ID def __str__(self): return self.ID thank you for the contributions -
How can I show related model property in Django admin?
I have two models, Retailer and Product like this: class Retailer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) website = models.CharField(max_length=255) description = models.TextField(default=None, null=True) def __str__(self): return str(self.id) class Product(models.Model): id = models.AutoField(primary_key=True) price = models.IntegerField(default=None, null=True) retailer = models.ForeignKey(Retailer,on_delete=models.CASCADE,related_name='products') is_active = models.BooleanField(default=False) def __str__(self): return str(self.retailer) + ' - ' + str(self.price) Now what I get is this: But what I want is showing Retailer name instead of Retailer id in Django admin, what should I do? -
-bash: manage.py: command not found while trying to run a git project
I am trying for the first time to run the project from the git. Here is the link to the project: https://github.com/spilab-umich/phishing-warning-experiment I followed all the suggested steps to deploy a Django on a host and it worked fine. I run: python manage.py runserver and after that wanted to come to the importing mail module,typing: python manage.py makemigrations mail I get the error message: -bash: manage.py: command not found Have anyone idea what I am doing wrong? How can I resolve this error? -
What is the best way to get a list of favorite articles by tags for a given user in django
I have a question. Lets say we have the following models: model User: pass model Article: text, ... tags = ManyToMany(Tag) model Tag: id, name, ... model Visits: hour = Integer(number of hours since epoch) article = ForeignKey(article) counter = IntegerField() In my client's local storage I have an array with the client's favorite tags. My question is: What would be the best way to query articles with the following criteria: The first ones to appear should be those who are related to the client's favorite Tags Then, There should be the rest of articles, without repeating the favorite ones Respectively, they should be ordered by "hot value", which is a summatory of the 24 latest models' counter related to each article I've put on my thinking cap for DAYS trying to come up with an efficien solution, but the best I've achieved takes entire seconds to query with a dataset of 10. Please, help. Also, off-topic, have I used correctly the expression "put on (one's) thinking cap"? English ain't my main languaje and I'm still learning! -
Do I need to place __ini__.py in each directory in a directory tree leading to my class?
I'm building a Django project with Python 3.6. I have created this directory structure ... project - commons - util - __init__.py - my_class.py The contents of init.py are from . import my_class In another class, I attempt to import my MyClass like this from commons.util import MyClass but I'm getting this error ModuleNotFoundError: No module named 'commons' Am I creating my init.py properly? -
Model Not showing in Django Admin created using built in AbstractUser
I have created a custom user model using Django built in User and I have added my own fields. When I try to run the code I am getting error. I have searched everywhere and I am not getting the answer to this error. I have run the code with empty admin.py it worked perfectly for LogIn/Logout and SignUp But nothing my showing in Django admin. Then after some research I came with the code mentioned below but Still I am getting error! models.py from django.db import models from django.contrib.auth.models import BaseUserManager,AbstractBaseUser class MyAccountManager(BaseUserManager): def create_user(self, email, username, address,phone_number,password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, address=address, phone_number=phone_number, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, address,phone_number,password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, address=address, phone_number=phone_number, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): email = models.EmailField(verbose_name="email",max_length=60,unique=True) username= models.CharField(max_length=30,unique=True) phone_number= models.IntegerField() address=models.CharField(max_length=300) is_active=models.BooleanField(default=True) is_admin=models.BooleanField(default=False) is_staff=models.BooleanField(default=False) is_superuser=models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','address','phone_number'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True forms.py from django.contrib.auth import get_user_model from … -
How can I get the current app's verbose name as a context variable in all templates in Django?
My django project has an app. The app's folder is main_menu_app. I didn't want to always have to type something like: {% url 'main_menu_app:PAGE' %} in templates, but rather {% url 'main_menu:PAGE' %} so inside my mysite/urls.py, I have this: path('main_menu/', decorator_include(login_required, ('main_menu_app.urls', 'main_menu'))), This names my app "main_menu". This works great in most cases. Unfortunately, recently, I acquired a need for adding the current app's verbose name to every template as a context variable. I can do this with a context processor, and normally, you can resolve the app you are in by doing: request.resolver_match.app_name unfortunately, mine resolves to "main_menu", and when I try to grab an app_config with that name (which contains the verbose name), it can't find it: from django.apps import apps app_name = request.resolver_match.app_name apps.app_configs[app_name] # KeyError: 'main_menu' apps.app_configs OrderedDict([..., ('main_menu_app', <MainMenuAppConfig: main_menu_app>), ...]) Is there some way I can resolve what I get back from request.resolver_match to an app_config? I know I can hard-code the main_menu_app name, but I'd rather do it dynamically, so it always works for all apps. -
Django check user permissions in serializer
I have a serializer that I'm trying to show all the granted permissions to the user for a particular project. I have it working in the serializer under different fields, but when I try to add them all together in a new field called my_permissions I get a list of every possible permission. I think it has something to do with my utils script, but I can't seem to figure out the issue. Here is my serializer: class ProjectSerializer(LightWeightSerializer): id = Field() name = Field() slug = Field() description = Field() created_date = Field() modified_date = Field() owner = MethodField() members = MethodField() is_private = Field() role_permissions = MethodField() anon_permissions = Field() public_permissions = Field() i_am_member = MethodField() i_am_admin = MethodField() my_permissions = MethodField() def get_members(self, project): members = Membership.objects.filter(project_id=project.id).select_related() return MembershipSerializer(members, many=True, context=self.context).data def get_i_am_member(self, project): members_list = Membership.objects.filter(project_id=project.id).select_related('user') for member in members_list: if member.user == self.context['request'].user: return True return False def get_role_permissions(self, project): members_list = Membership.objects.filter(project_id=project.id).select_related('user') for member in members_list: if member.user == self.context['request'].user: return RoleSerializer(member.role).data['permissions'] return [] def get_i_am_owner(self, obj): if "request" in self.context: return is_project_owner(self.context["request"].user, obj) return False def get_i_am_admin(self, project): members_list = Membership.objects.filter(project_id=project.id).select_related('user') for member in members_list: if member.user == self.context['request'].user: if member.is_admin: return True … -
How to render a pdf file as pdf in browser using django
I am using Django web frame work. I am taking pdf files from users (notes/book/etc). Then I want to display those pdf in website, but I could not find a way. Methods that failed 1)iframe 2)simple rendering using django 3)pdf.js library. Also browser blocks rendering initially. Care to suggest a method and steps to implement it.