Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamicall add/remove multiple Django nested inline formsets with angularJS
How to dynamically add/remove multiple nested inline formsets with angularJS in Django? See "Desired Result" below Scenarios: I have a basic flow form with a field called "basicDescription". Below this form is a related Alt Flow form with its field called "altDescription. If I click "+ Add Alt Flow", it should add another related Alt Flow form to the basic flow. Conversely, if I click "- Remove Alt Flow", it should remove the related Alt Flow form from the basic flow. If I click "- Remove Basic Flow", it should remove the basic flow form along with any related Alt Flow forms. Conversely, if click "+ Add Basic Flow", it should display default nested form set view as the example below. Desired Result: Basic Flow 1 basicDescription:________________ - Remove Basic Flow Alt Flow: altDescription:______________ - Remove Alt Flow + Add Alt Flow + Add Basic Flow -
Serialization and permissions in Django Rest Framework
I'm new in Django and DRF, have questions with serialization. I have models: class Commodity(models.Model): shop = models.ForeignKey(Company, on_delete=models.PROTECT) price = models.DecimalField(max_digits=10, decimal_places=2) active = models.BooleanField(default=False) class Clother(models.Model): commodity = models.ForeignKey(Commodity, related_name='commodity', on_delete=models.CASCADE) color = models.ManyToManyField(Color, related_name='color') material = models.ManyToManyField(Material, related_name='material') gender = models.CharField(max_length=2, choices=GENDER_CHOICES, default=UNISEX) class Outwear(models.Model): clother = models.ForeignKey(Clother, on_delete=models.CASCADE) name = models.CharField(max_length=30, blank=True) outwear_type = models.ForeignKey(OutwearType, on_delete=models.CASCADE) size = models.ManyToManyField(ClotherSize) So I suppose to make a Serializer like that: class OutwearSerializer(serializers.ModelSerializer): commodity = CommoditySerializer(many=False, read_only=False) clother = ClotherSerializer(many=False, read_only=False) class Meta: model = Outwear fields = ('commodity', 'clother', 'name', 'outwear_type', 'size') As I understand that read_only fields let me add or edit Outwear object further, but I supposed to have 2 types of permition: All users can see only active Commodity objects. Only Companies can create and edit their own objects. Do I need to make 2 Serializer Models for read_only=True/False? What is the best practice and where can I find good examples of something familiar? Thanks! -
Django redis for notifications
I have build a REST API with django rest framework. In the app there is a need for facebook-type notifications ( new friend request, new message etc. ). Currently i'm handling this using long-polling: - front client sends GET request - my REST view searches for new objects and returns them instant if there are any , else its searching for 20 seconds and returns empty response if there are None - a new GET request is sent instant after the response is received ( from the front client ) ** NOTE: we are not using websockets , if needed please write me I want to replace this method with django/redis since i think my long-polling method is abusing the DB a lot and i think Redis with its speed and structure can help a lot. Are there any suggestions on how would i acomplish something like this ? -
How to reverse username in template tag i.e <a href=" "> in django?
So, what I want is to be able to reverse the user to the profile page when he clicks the tag. I've tried : href="{% url 'profile/' <username> %} href="{% url 'profile/' signups.username %} but, I'm getting TemplateSyntaxError. -
Check multiple decorators before accessing a view in django
Im using @user_passes_test decorator to check whether the user has permissions to the view. Each usertype is given a function that is used with the decorator. Like this @user_passes_test(ismanager,login_url='userauth:forbiddnpage') @user_passes_test(isadministrator,login_url='userauth:forbiddnpage') Now, if the first one returns false the forbidden page is shown. Is there any way i can get all the decorators to get checked before redirecting or giving access. Thanks for the help. -
How can I express a foreign key as a pair in Django?
Here are some Django models: class User (Model): name = CharField (max_length=100) class ThingVersion (Model): timestamp = DateTimeField (auto_now_add = True) class ThingPartition (Model): version = ForeignKey (ThingVersion) partition_number = IntegerField () class UserInPartition (Model): user = ForeignKey (User) version = ForeignKey (ThingVersion) partition_number = IntegerField () class Meta: unique_together = (('user', 'version')) I have deliberately not done the "obvious" thing, which is this class UserInPartition (Model): user = ForeignKey (User) partition = ForeignKey (ThingPartition) because I require the unique_together constraint, which AFAIK isn't possible to express if I use the more-normalized partition = ForeignKey (ThingPartition) approach. How do I express that the UserInPartition.(version,partition_number) pair is a foreign key to ThingPartition? Alternatively, is there a way to use the normalized partition = ForeignKey (ThingPartition) approach and constrain the UserInPartition model to only have one partition_number per (user,version)? -
How to run Django App on cloned EC2 AWS
I have recently taken over a project for a small startup. The application is a django based website running on AWS ec2 instance. To carry out my work I cloned this instance and created a second "testbox" instance. The testbox instance is running but when i navigate to the the public ip it shows nothing. Am i missing a command to boot the django app inside the EC2 instance? This is all new to me, so any help would be much appreciated. Lee -
Django static files - Changing URL
I'm a little confused with Django's static files. I understand they are not served in development however in my production environment I have tried everything to change the URL for the files which are being server. It just doesnt make any sence to me. Everything is still being served via /static/ with my URL's even after changing STATIC_URL. settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'dsadsa') STATIC_URL = '/ddd/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'app/static'), ] From those setting I expect all my static files to end up inside of a directory called dsadsa and server with a url www.example.com/ddd/file.css however this is just not the case they always get served via www.example.com/static/file.css from the directory staticfiles. I'm running this project in Heroku with no Debug = False Can anyone please help me understand what on earth I'm missing here? -
Django offical tutorial models part4
Hi i following djangoproject offical tutorials in part 4 it use question.choice_set Statment i don't know what is mean choice_set can anyone help me? Can I use question.Objects for example instead of question.choice_set? thanks -
django for production of my recommender system
I have written an content_based recommender system in python3 using the data from a mysql database. Now i have to use django for production so that I need not to take input each time new articles are added in the database. How to convert this python code into django production. i will connect the database with django database connections. I am really confused how to write this code in django? my_recommender_system import pandas as pd import re from nltk.tokenize import word_tokenize, sent_tokenize from nltk.corpus import stopwords stop = set(stopwords.words('english')) from string import punctuation import functools from matplotlib import pyplot as plt from nltk.stem.snowball import SnowballStemmer stemmer = SnowballStemmer("english", ignore_stopwords =True) from tqdm import tqdm_notebook tqdm_notebook().pandas() import numpy as np import math from sklearn.metrics.pairwise import linear_kernel #import text from collections import Counter df = pd.read_csv('target.csv') df = df.loc[:,['id','combined_text']].astype(str) df["combined_text"] = df["combined_text"].apply(lambda x: ' '.join(pd.unique(x.split()))) df.combined_text = df.combined_text.apply(lambda x: x.lower()) df.combined_text = df.combined_text.str.replace('[^\w\s]',' ') df['combined_text'] = df['combined_text'].str.replace('\d+', ' ') df.combined_text = df.combined_text.str.replace('nbsp?' , ' ') #df.combined_text = df.combined_text.str.replace('nan?' , ' ') df.combined_text = df.combined_text.str.replace('value?' , ' ') df = df.dropna(subset = ['combined_text']) df.combined_text = df.combined_text.str.replace('\s+', ' ') #df.combined_text.map(len).hist(figsize=(15, 5), bins=100) df = df[(df.combined_text.map(len) > 600)] df.reset_index(inplace=True, drop=True) #df1 = df[(df.combined_text.map(len) > 7500)] … -
Django development server dramatically slowed down
I have a project that was running normally until now when the code base has developed, now running very slow. I don't know what is wrong with it Command like python manage.py runserver takes 3 minutes to load Project dependencies amqp==2.2.2 anyjson==0.3.3 appdirs==1.4.3 autopep8==1.3.5 billiard==3.5.0.3 cached-property==1.4.2 celery==4.2.0rc3 certifi==2018.4.16 chardet==3.0.4 defusedxml==0.5.0 dj-database-url==0.5.0 Django==2.0.6 django-annoying==0.10.3 django-celery-beat==1.1.1 django-cors-headers==2.2.0 django-heroku==0.3.1 django-redis==4.9.0 django-silk==3.0.0 djangorestframework==3.8.2 djangorestframework-xml==1.3.0 gprof2dot==2016.10.13 gunicorn==19.8.1 idna==2.6 isodate==0.6.0 Jinja2==2.10 kombu==4.1.0 lxml==4.2.1 Markdown==2.6.11 MarkupSafe==1.0 psycopg2==2.7.4 psycopg2-binary==2.7.4 pycodestyle==2.4.0 PyConfigure==0.5.9 Pygments==2.2.0 PyStaticConfiguration==0.10.3 python-dateutil==2.7.3 pytz==2018.4 PyYAML==3.12 redis==2.10.6 requests==2.18.4 requests-toolbelt==0.8.0 six==1.11.0 sqlparse==0.2.4 structlog==18.1.0 urllib3==1.22 vine==1.1.4 whitenoise==3.3.1 zeep==2.5.0 -
SyntaxError: invalid syntax Django-app deployment
I check the documentation but still the problem unsolved. Invalid syntax in my forms.py file from django import forms from blog.models import Post,Comment class PostForm(forms.ModelForm): class Meta(): model = post fields = ('author', 'title','text') widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea postcontent'}) } class CommentForm(forms.ModelForm): class Meta(): model = Comment fields = ('author', 'text') widgets = { 'author': forms.TextInput(attrs={'class':'textinputclass'}) 'text': forms.Textarea(attrs={'class':'editable medium-editor-textarea'}) } I was trying to deploy my first django application (study purpose). Almost finish it when comes this error. -
Scripts for Python are not on PATH
So I am new to Python (and programming in general) and I am trying to install it on my Mac. Forgive me if I might ask silly questions. I currently have Python 3.6 and django 2.0 installed with it - I just installed virtualenv and pipenv which I don't get the difference but my terminal says that those scripts are not on PATH. How do I add those directories to the PATH and how can I check that they are on the right path? Do I need something more before starting to code? Thanks! -
Define name space in DRF routes
I need to define a custom namespace for DRF routes. Let suppose I have following route. from rest_framework import routers router = routers.SimpleRouter() router.register(r'users', UserViewSet) Now if I want to define name space like user-create, add-new-user, update-user, delete-a-user. Then how can I do this? -
sending email after verification using django-allauth
I'm using django-allauth (registration, login, e-mail verification are working). Now I'm trying to send additional e-mail after profile verification. Is there a simple way to do this with allauth? Regards -
How can I access Python session by php to make sure that the user is authenticated and logged in?
Suppose we have a web application using Python and Django that the user uses to log in to the application and uses the menu and the dashboard. On the other hand, part of the program is written with PHP. Now we want to put the PHP-written part in, using the iFrame in the dashboard written with Python. How can I access Python session by PHP script to make sure that the user is authenticated and logged in? Thank you in advance... -
Django modelform: single view for inserting and updating?
I am new to Django and not sure what the best way is to go about this. I am using a ModelForm to create forms for inserting/updating. However, my question is if I should have a single view for both operations, or if it is best to have two separate ones? EXAMPLE SEPARATE VIEWS: def insert(request): form = ModelForm(request.POST or None) if form.is_valid(): form.save() return redirect('next_view') context = { 'form': form} return render(request, 'modelform.html', context) def update(request, id): instance = Model.objects.get(id=id) form = ModelForm(request.POST or None, instance=instance) if form.is_valid(): form.save() return redirect('next_view') context = { 'form': form} return render(request, 'modelform.html', context) EXAMPLE SINGLE VIEW def modelform(request, id=False): if id: instance = Model.objects.get(id=id) form = ModelForm(request.POST or None, instance=instance) else: form = ModelForm(request.POST or None) if form.is_valid(): form.save() return redirect('next_view') context = { 'form': form} return render(request, 'modelform.html', context) What is the recommended way of doing this? I feel the combined view is simpler, but not sure what the best way is of doing this. Also, if there are any other comments on this code please let me know. Using Django 2.0. -
regular expression matches the requirement (000)000-0000, but not saved in the backend?
Regular expresson not working properly (not storing in db) but it works for other regex like /./ (store in db) The code is in ember js, and backend is Python Django. When i proceed with '', it is accepted and phone number is saved if(value == 'phone'){ if(this.get('user.phone').length>0){ if (( /^\(\d{3}\)\s\d{3}-\d{4}$/.test(this.get('user.phone'))) ){ const user_obj = { phone: this.get('user.phone'), sessionid: localStorage.getItem('session_id'), } set(this, 'pass_user', user_obj); this.set('invalidPhone', false); } else{ this.set('invalidPhone', true); } } else{ this.set('invalidPhone', false); } } Here is the django code for saving the data class SaveOfficeSpaceAPIView(APIView): def post(self, request, *args, **kwargs): session_id = request.POST.get('sessionid') own_obj = SearchWarehouse.objects.get(session_id=session_id) office_space = request.POST.get('officespace') loading_dock = request.POST.get('loadingdock') transportation_services = request.POST.get('transportation_services') warehouse_equipment = request.POST.get('warehouse_equipment') technology_services = request.POST.get('technology_services') name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') need = request.POST.get('need') if office_space: if office_space == 'Yes': own_obj.office_space = True else: own_obj.office_space = False if loading_dock: if loading_dock == 'Yes': own_obj.loading_dock = True else: own_obj.loading_dock = False if transportation_services: if own_obj.transportation_services == True: own_obj.transportation_services = False else: own_obj.transportation_services = True if warehouse_equipment: if own_obj.warehouse_equipment == True: own_obj.warehouse_equipment = False else: own_obj.warehouse_equipment = True if technology_services: if own_obj.technology_services == True: own_obj.technology_services = False else: own_obj.technology_services = True if name: own_obj.name = name elif email: own_obj.email = … -
Django: OneToOne dropdown in the admin interface and unique associations
Referring to Django - one-to-one modelAdmin i am still searching for a solution to my problem with the admin interface of Django and my OneToOne relationship. I have the following model which extends the standard User model with an additional attribute is_thing_staff: class ThingStaff(models.Model): """ Extends the django user model by a separate model relationship which holds additional user attributes """ user = models.OneToOneField(User, on_delete=models.CASCADE) # by default a new user is not a staff member which take care of the thing administration is_thing_staff = models.BooleanField(default=False) def __str__(self): return u"{}".format(self.user.username) class Meta: verbose_name = "Thing Staff" verbose_name_plural = "Thing Staff" If i create a new ThingStaff object in the django admin interface, i can select all users, even if there is already a relationship for a user. Saving a new object with a duplicate association to a user results in an error, that there is already an ThingStaff object associated with that User. So far this is more or less ok. But why show up possible selections if they would result in an error in the next step? So i excluded them via from django import forms from django.contrib import admin from .models import ThingStaff class ThingStaffForm(forms.ModelForm): def __init__(self, *args, … -
Django Rest Framework: How to pass a list of uuid's for a nested relationship to a serializer?
TLDR: What could be the reason the incoming data for one of my serializers does not get processed? I'm working on a serializer for a nested relationship. The serializer should get a list of UUIDs, so that I can make many to many relationships. Here is the model: class Order( UniversallyUniqueIdentifiable, SoftDeletableModel, TimeStampedModel, models.Model ): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) custom_choice_items = models.ManyToManyField(CustomChoiceItem, blank=True) price = models.ForeignKey(MenuItemPrice, on_delete=models.CASCADE) amount = models.PositiveSmallIntegerField( validators=[MinValueValidator(MINIMUM_ORDER_AMOUNT)] ) Here is the data with which I hit the route in my tests: data = { "checkin_uuid": self.checkin.uuid, "custom_choice_items": [], "menu_item": self.menu_item.uuid, "price": self.menu_item_price.uuid, "amount": ORDER_AMOUNT, } response = self.client.post(self.order_consumer_create_url, self.data) Note that the empty list for custom_choice_items does not change anything. Even if I fill it with values the same error occurs. And last but not least here are the serializers: class CustomChoiceItemUUIDSerializer(serializers.ModelSerializer): """Serializer just for the uuids, which is used when creating orders.""" class Meta: model = CustomChoiceItem fields = ["uuid"] .... # The serializer that does not work class OrderSerializer(serializers.ModelSerializer): menu_item = serializers.UUIDField(source="menu_item.uuid") custom_choice_items = CustomChoiceItemUUIDSerializer() price = serializers.UUIDField(source="price.uuid") wish = serializers.CharField(required=False) class Meta: model = Order fields = [ "uuid", "menu_item", "custom_choice_items", "price", "amount", "wish", ] The problem is now, that when I leave … -
Django redirecting from unknown reason
I was working on this app some time back and I have returned and for the life of me cannot see where a redirection is occurring. From starting the app as below and navigating to the base URL, you can see attempt to reach '/Sites/' url python manage.py runserver Performing system checks... System check identified no issues (0 silenced). June 20, 2018 - 16:35:05 Django version 1.11.13, using settings 'SysMan.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Not Found: /Sites/ [20/Jun/2018 16:35:07] "GET /Sites/ HTTP/1.1" 404 2263 The urls file is as below. from django.conf.urls import include, url from django.contrib import admin from django.views.generic.base import RedirectView from django.contrib.auth import views as auth_views admin.site.site_header = 'Rio Tinto System Management' admin.site.site_title = 'RioTinto SysMan admin' admin.site.index_title = 'SysMan Administration' urlpatterns = [ url(r'^$', RedirectView.as_view(url='/main/', permanent=True)), url(r'^admin/', admin.site.urls), url(r'^main/', include('apps.main.urls')), url(r'^asnreg/', include('apps.asnreg.urls')), ] I have run grep against the project folders for 'Sites' with nothing of meaning being returned there. Manually browsing to the URL's as below get me where I need to be. http://127.0.0.1:8000/admin/ http://127.0.0.1:8000/main/ http://127.0.0.1:8000/asnreg/ Just can't figure why http://127.0.0.1:8000/ redirects me to http://127.0.0.1:8000/Sites/ I have looked at the various views file with nothing obvious there either I … -
django drf Serialize List<String> get from android
django 2.0.2 python 3.4 MySerilaizer(serializers.Serailzier): Tags = serializer.ListField() Android Send Type @Field("Tags") List<String> tags but raise error Incorrect type. Expected list, received str so i changed Tags = serializer.CharField() CharField is worked but get last value of list not list just str -
Django forms ModelChoiceField, filtering by category and item
In my model (Expenses) I have categories defined that I would like to use as presets/defaults in the creation form of another App (Foods). Oddly the current code outputs a list of Usernames instead of the Expense Category (along the lines of what I want but I want the item instead of teh expense_category of the Expense Model). If I apply .all() to the end of the ModelChoiceField queryset, I get nothing back(probaby expected as I'm doing something wrong). Foods App -> forms.py class FoodForm(forms.ModelForm): item = forms.ModelChoiceField(queryset=Expense.objects.filter(expense_type='Food')) class Meta(): model = Food fields = ['item','servings','calories','create_date'] Foods App -> views.py class FoodCreateView(LoginRequiredMixin, CreateView): model = Food fields = ['item','servings','calories','create_date'] login_url = 'accounts/login.html' # Filter by User def form_valid(self, form): form.instance.user = self.request.user return super(FoodCreateView, self).form_valid(form) Expenses App -> models.py class Expense(models.Model): BILLS = 'Bills' FOOD = 'Food' PERSONAL = 'Personal Care' MISC = 'Misc' CATEGORY = ( ('Food','Food'), ('Bills','Bills'), ('Personal Care','Personal Care'), ('Misc','Misc'), ) user = models.ForeignKey(User, related_name='exp_user') amount = models.IntegerField() item = models.CharField(max_length= 50) expense_type = models.CharField(max_length =15, choices=CATEGORY, default=FOOD) create_date = models.DateField(default=datetime.date.today) It would be ideal if I could filter by Expense Type for 'Food' and then populate by the item I'm also guessing that doing this in … -
Django admin+dropdown+ForeignKey+delete override
So all is good in django and the project I am currently trying to get my head around, but the problem is as follows. 1) I have ovreriden the is_delete() method in django to show a green tick in the admin list display and not actually delete the query from the database. 2)I have a foreign key relation of model A with model B. Now whenever i Delete an entry from model B, that particular entry is still showing itself in the Admin panel of Model B's dropdown list. I want queries of model A to not show in the foreignkey dropdown list of Model B. All the help and suggestions are welcome. Thanking in Advance.! P.S.- Python version is 3.5, Django version is 2.05, I am not using any view or not even any forms. This problem is only for django Admin section. -
django error 0x03EBE150
Unhandled exception in thread started by check_errors..wrapper at 0x03EBE150> Traceback (most recent call last): File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 399, in check for pattern in self.url_patterns: File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 540, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 533, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "C:\Users\Irfan\Desktop\mysite\mysite\urls.py", line 20, in path('polls/', include('polls.urls')), File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\Users\Irfan\AppData\Local\Programs\Python\Python36-32\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", …