Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - ManyToManyRelationships
Can u simplify why we create many to many relationships between models?like tags=ManyToManyRelationship(Tag) what does it do? -
django admin add error to form field
I have the following code: Model: class MyUser(AbstractUser): profile = models.OneToOneField(Profile, null=True, on_delete=models.PROTECT) My profile model contains only some personal fields like full_name, gender, birthdate, etc. Admin: class MyUserInline(admin.StackedInline): model = MyUser fieldsets = ..... filter_horizontal = .... class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = MyUser def clean_password(self): return "" class ProfileAdmin(admin.ModelAdmin): inlines = (MyUserInline,) change_user_password_template = None form = MyUserChangeForm change_password_form = AdminPasswordChangeForm def save_model(self, request, obj, form, change): if not Profile.objects.filter(myuser__username=obj.myuser.email).exclude(pk=obj.id).exists(): obj.myuser.username = obj.myuser.email obj.save() else: # *MY PROBLEM IS HERE!* What I am going to do is to delete username field from admin change user page and set their email as their username as well. In AbstractUser email is not unique but username is. The problem is when changing a user email, if email is duplicated it would raise exception, but I want to show error to say this email is duplicated. Is the only way to do that changing my MyUser model and add email as a unique field or I can do something else? tnx -
Recursively search all fields of articles for a q
There are four model tables in my database: Block which defines the major themes Article which foreignKey to Block Comment ForeignKey to Article Footnotes ForeignKey to Article and Comment respectivley Tag many-to-many relationship with Article The details: class Block(models.Model): name = models.CharField("block name", max_length=100) desc = models.CharField("block description", max_length=100) admin = models.CharField("block admin", max_length=100) status = models.IntegerField(choices=STATUS) class Article(models.Model): tags = models.ManyToManyField(Tag, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) block = models.ForeignKey(Block, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() # set the widget status = models.IntegerField(choices=STATUS, default=1) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) class Comment(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE) body = models.TextField() # set the widget status = models.IntegerField(choices=STATUS) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) class Footnote(models.Model): content = models.TextField() article = models.ForeignKey(Article, blank=True, null=True, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, blank=True, null=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) class Tag(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=50, unique=True) I am defining a views.search to retrieve all the articles which contain the searching information in every corner of their fields qualified_articles = (Article.objects .filter(Q(owner__icontains=q) | Q(block__icontains=q) | Q(title__icontains=q) | Q(content__icontains=q) | Q(comment__body__icontains=q) | Q(tag__name__icontains=q) | Q(footnote__content__ficontains=(q)), ... ) ) I manually listed all the fields, Since I am looking up … -
django admin change user password
I am new to django. I have the following codes: model: class MyUser(AbstractUser): profile = models.OneToOneField(Profile, null=True, on_delete=models.PROTECT) My profile model contains only some personal fields like full_name, gender, birthdate, etc. admin: class MyUserInline(admin.StackedInline): model = MyUser exclude = ('first_name', 'last_name', 'username', 'plan', 'password') fieldsets = ( (_('Personal info'), {'fields': ('email',)}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = MyUser def clean_password(self): return "" class ProfileAdmin(admin.ModelAdmin): inlines = (MyUserInline,) change_user_password_template = None form = MyUserChangeForm change_password_form = AdminPasswordChangeForm ordering = ('myuser__email',) def save_model(self, request, obj, form, change): obj.myuser.username = obj.myuser.email obj.save() list_display = ('full_name', 'myuser_email', 'myuser_is_staff', 'myuser_is_superuser', 'myuser_is_active') def user_change_password(self, request, id, form_url=''): if not self.has_change_permission(request): raise PermissionDenied user = self.get_object(request, unquote(id)) if user is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % { 'name': force_text(self.model._meta.verbose_name), 'key': escape(id), }) if request.method == 'POST': form = self.change_password_form(user, request.POST) if form.is_valid(): form.save() # rest of method # other minor methods I cannot change user password, at first the change password page doesn't open at all (Profile with ID "3/password" doesn't exist. Perhaps it was deleted?) after adding the following code it opens, but after pressing save button, … -
Django - 'user' is an invalid keyword argument for this function
I made a custom user registration form and I'm getting the error - "user" is an invalid keyword argument for this function on this line in models.py new = Profile.objects.create(user=instance) I've attached all the code below forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=254, required = False) age = forms.IntegerField(required = False) class Meta: model = User fields = ('username', 'email', 'age', 'password1', 'password2') def save(self,commit = True): user = super(SignUpForm, self).save(commit = False) user.email = self.cleaned_data['email'] user.age = self.cleaned_data['age'] if commit: user.save() return user models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.TextField(max_length=500, default = "", blank=True) age = models.IntegerField(default=-1, blank=True) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password1'] email = form.cleaned_data['email'] age = form.cleaned_data['age'] form.save() user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect('profile') else: form = SignUpForm() return render(request, "signup.html", {'form': form}) -
effect of static files in django not seen immediately
I am using django 2.0.7. My folder structure is like The project folder is mysite and inside that I have a app installed polls. Inside polls I have all the all the usual files. I have a templates and static folder and inside both of these there is a polls folder. Inside the polls folder again I am storing my static and template files.So the overall structure is like this- mysite polls template polls index.html static polls style.css Now I want to use css file for index.html. so I added this line in index.html. {% load static %} <link type="text/css" rel="stylesheet" href="{% static 'polls/style.css' %}"> Now whatever I am doing in css file that is showing in the browser but the problem is its not instantaneous. I mean right now if I change the color of a para to yellow and then reload the page then I cannot see the effect immediately. I have to wait for some time. I also included this in the settings file STATIC_URL='/static/' STATICFILES_DIRS=[os.path.join(BASE_DIR,'static'),] -
How to decode this wierd encoding in python?
Hi I am working with a mobile operator api. When I receive a message in Persian it returns a weird encoding like this. 062a0633062a this string represents "تست" in Persian. I know every four character is unicode representation of Persian character. how can I decode this kinda encoding? thanks in advanced. -
uWSGI always redirecting on https
I am deploying a demo Django application on aws ubuntu 16 EC2 instance. So I just want my app to run on http. When i ran it using python manage.py runserver 0.0.0.0:8000, it executes fine. But when I ran the application using uwsgi --http :8000 --module mysite.wsgi, it always redirects to http eg. I entered my_ec2_ip:8000, it always redirects to https://my_ec2_ip:8000. I also tried http://my_ec2_ip:8000 but same problem. Also now when i try with manage.py command it redirects to https for 8000 port but works fine for other ports. Also I confirmed that this happens with other ports as well that it redirects to https when i run uwsgi command using that port. -
Reverse for 'add_to_cart' with arguments '('',)' not found. 1 pattern(s) tried:
I am creating an ecommerce site. I have a product detail page that has a button on it which points to the method "add_to_cart". Add to cart requires an item_id pk in the URL, in order to add that item to the corresponding order_item to order object. Why is the ProductDetailView returning the following error when I add the get_context_data function to its class based view Error: Exception Value: Reverse for 'add_to_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['checkout/add-to-cart/(?P<item_id>[-\\w]+)/$'] portal/views.py from django.shortcuts import render, redirect from django.shortcuts import render from django.views.generic import CreateView, DetailView, ListView, RedirectView, UpdateView from django.views import generic from django.contrib.auth.decorators import login_required # This is to block pages to non users using function views from django.contrib.auth.mixins import LoginRequiredMixin from .forms import ProductForm, ContactForm from .models import Product, Contact from checkout.models import OrderItem, Order from users.models import User, Profile # Create your views here. class ProductDetailView(generic.DetailView): model = Product template_name = 'portal/product_detail.html' def get_context_data(self, **kwargs): #item_id = self.kwargs['pk'] filtered_orders = Order.objects.filter(owner=self.request.user.user_profile, is_ordered=False) current_order_products = [] if filtered_orders.exists(): user_order = filtered_orders[0] user_order_items = user_order.items.all() current_order_products = [product.product for product in user_order_items] #not sure what this does context = { 'current_order_products': current_order_products } return context portal/views.py url(r'^product/(?P<pk>\d+)$', views.ProductDetailView.as_view(), … -
how to install and use mod_wsgi for py3 in yum
I use mod_wsgi in aws what use package manager yum. so I commanded 'yum install mod_wsgi' but It installed mod_wsgi for py2 always. ============================================================================================== Package Arch Version Repository Size ============================================================================================== Removing: mod_wsgi-python26 x86_64 3.2-6.11.amzn1 @amzn-main 175 k Transaction Summary ============================================================================================== how can I install and use mod_wsgi for py3. -
Django - create child models
Let say that the model name is BHA, and I populate this field. In Django-Admin homepage, I will have a tab looks like this: MY_APP_NAME BHA List Other Model 1 Other Model 2 Upon clicking BHA List, I will be navigate to a page that has a list of populated BHA: BHA List BHA_1 BHA_2 BHA_3 BHA_4 And each BHA needs a separate table that has their own information. So all BHA's (BHA_1, BHA_2, BHA_3, BHA_4) will have exact same child field Bit data, Sensor Data, Component Data. And Each of these sub-fields will have its own subfields too. How should I design my models.py to make this work? Can anyone provide any example code set that enables this feature? So far I know only a really basic models.py structure that looks like this: class SomeModel(models.Model): field_1 = models.CharField(max_length=100, primary_key=True) field_2 = models.CharField(max_length=100) field_3 = models.CharField(max_length=100) -
Django-Upload file from HTML form to specific directory without using Django Forms
I can upload file and images from Admin panel and it looks in the specified directory but when I do so from the HTML form everything gets saved except the file. From Django admin panel, the file gets saved to media folder and I can access it from the template.But when I try to upload from Html form in my template, it doesn't get uploaded but everything else like comment, category, and status does. My models: from django.db import models from datetime import datetime class File(models.Model): title=models.CharField(max_length=200) document=models.FileField(upload_to='media') comments=models.TextField() uploaded_at=models.DateTimeField(default=datetime.now,blank=True) category=models.CharField(max_length=200,default="Education") status=models.CharField(max_length=200,default="Completed") def __str__(self): return self.title My app.urls: from django.conf.urls import url,include from . import views urlpatterns=[ url(r'^$',views.index,name="index"), url(r'^search/$',views.search,name="search"), url(r'^searchdate/$',views.searchdate,name="searchdate"), url(r'^addfile/$',views.addfile,name="addfile"), url(r'^delete-entry/(?P<pk>\d+)$', views.DeleteView, name='delete_view'), ] my urls: from django.contrib import admin from django.urls import path from django.conf.urls import url,include from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings urlpatterns = [ url(r'admin/', admin.site.urls), url(r'^$',include('domsapp.urls')), url(r'^files/',include('domsapp.urls')), ] urlpatterns+=staticfiles_urlpatterns() urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) My settings: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') My html form: <form class="addForm" method="POST" action="/files/addfile/"> {% csrf_token %} <input type="file" name="fileadded" id="fileinput" placeholder="Choose File"> <hr> <label id="#titleLabel">Title</label> <hr> <input type="textarea" name="title" placeholder="Enter Title" class="addinput" required> <hr> <label id="#commentLabel">Comments</label> <hr> <textarea name="comments" class="addinput comment-input" required=""></textarea> <hr> <label … -
Is there a way to use data from a completed PayPal payment on the website?
I just successfully integrated Django-paypal in my website. This is for an auction style payment system in which a user(probably not authenticated but can be) can choose an item, bid on it, and complete the payment through PayPal. The action of bidding creates a Bid object: class Bid(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) anonymous = models.BooleanField(default=True, choices=yesno_choices) bidder_name = models.CharField(max_length=100, null=True, blank=True) amount = MoneyField(max_digits=14, decimal_places=2, default_currency='USD') class Meta: ordering = ['anonymous', 'bidder_name', 'item', 'amount'] def __str__(self): return self.item Now this bid object gets created whether or not a successful payment is made, which would not be a problem if not for the fact that I've implemented a model function for Item which checks the number of bids, their respective amounts, and totals it all up so that this number can be displayed on the website: def get_bid_total(self): total_amount = 0 if Bid.objects.exists(): bid = Bid.objects.filter(item=self.name) for b in bid: total_amount += b.amount return total_amount else: pass Of course this counts ALL bids, not just successful ones. What I need is some way to update the bid object so that it will show if it was successful or not, and then only count the successful bids in the get_bid_total function. I'm … -
Trouble installing psycopg2-binary: EnvironmentError
So, I'm trying to install psycopg2-binary as that is a warning I get for heroku. When I run this command pip install psycopg2-binary I got this error: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: 'C:\\Users\\djangoproject\\Lib\\site-packages\\psycopg2\\_psycopg.cp36-win32.pyd' Consider using the--useroption or check the permissions. I'm the only user on my computer and so I don't understand this error: I did try runing pip install psycopg2-binary --user, but got a similar error. I have a virtual env open and am installing it in that. The django project will have a postgress database in prod, but not in local. -
How to continue function if Django object can't be found
I want to check if an object exists - if it doesn't exist I want to still continue the function and not return a 404 error. How can I achieve this? def check(request): if request.is_ajax(): # print('Working') #prints id = request.POST.get('id') post = Post.objects.get(hash=id) obj = get_object_or_404(Post, post=post) if obj: # do stuff else: #do something else The above code returns: Not Found: /check/ [22/Jul/2018 01:15:03] "POST /check/ HTTP/1.1" 404 1729 -
How should I advance my project once after deploying into AWS elastic beanstalk?
I have been creating my project using Django. I deployed the project into AWS elastic beanstalk. And now I'm wondering how I should advance my project. I mean after deploying into AWS elastic beanstalk, any changes can not be reflected unless I commit the changes on git. So I am wondering if I have to commit to git every time I want to change the project and check if the change does work. Or is there a better way to do it? How do people usually advance project and change the project and check if the changes do work well? -
Django unique "username" when using local user authentication and "Django Social auth" application
I am using Django local user registration as well as some social media authentication using Django-social_auth webapp. When I go to user table to check the usernames, It looks to me that Django might compromise the uniqueness of the username. For example, if i have two emails "abcdef@gmail.com" and "abcdef@yahoo.com" how would it store such things in the user table as it stores "abcdef" part in the username column. -
Delete object from Django sqlite3 database, reducing the database size
I have a table with many entries. I can very easily "delete" those entries, such that they no longer appear when using the Django Admin page. However, these records are still in the .sqlite3 file. I would like to reduce the .sqlite3 file size as a result of my deletion. Google searches are so far fruitless on the topic. -
How to save in a single post two table OnetoOne - Django
I have 2 models: class User(AbstractUser): TYPES = (('A', 'Administrador'), ('P', 'Persona'), ('C', 'Corporativo'), ('E', 'Emprendedor'), ('R', 'Reciclador')) login_type = models.CharField(max_length=1, blank=True, null=True) account_type = models.CharField(max_length=1, choices=TYPES, blank=True, null=True) picture_url = models.CharField(max_length=200, blank=True) is_deleted = models.BooleanField(default=False) class EcoUser(models.Model): user = models.OneToOneField(User, related_name='eco_user') document = models.CharField(max_length=45, blank=True) phone_number = models.CharField(max_length=45, blank=True) ubigeo = models.CharField(max_length=6, blank=True) address = models.CharField(max_length=500, blank=True) location = models.CharField(max_length=200, blank=True) def __str__(self): return str(self.user) In which when I want to add a User it is also saved in EcoUser I thought that putting together in the ** serializer ** the two models and using a generic of ** create ** would work like this: class UserSerializer(serializers.ModelSerializer): def to_representation(self, instance): representation = super(UserSerializer, self).to_representation(instance) eco_user = EcoUser.objects.filter(user_id=instance.id)[0] representation['document'] = eco_user.document representation['phone_number'] = eco_user.phone_number representation['ubigeo'] = eco_user.ubigeo representation['address'] = eco_user.address return representation class Meta: model = User fields = ('id', 'username', 'password', 'first_name', 'last_name', 'email', 'login_type', 'account_type', 'picture_url', 'is_deleted' ) extra_kwargs = {'password': {'write_only': True, 'required': False}} however, it only served to list but not to create. this is my viewset: class EcoUserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.exclude(is_deleted=True) pagination_class = None @transaction.atomic def create(self, request, *args, **kwargs): with transaction.atomic(): try: data = request.data serializer = self.get_serializer(data=data) if serializer.is_valid(raise_exception=True): serializer.save() … -
Django-El-Pagination Renders my Nav Bar and another table on every "more" click
In hopes to speed up my TTFB, I have turned to using pagination, hoping Django-el-pagination will fix my issues with rendering 100s of objects to a table. I am having some issues getting this running correctly. When I first load my page, everything looks great, shows the correct amount of objects in my table along with a more link. When I click more, the next set of objects are shown, however they are appended into my <table> as a whole page! This means, my navbar and table get rendered inside of my already `'. I am so confused why it is doing this, and it must be something simple. Thank you in advance, I really hope someone can help me. I have a base.html... <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> {% load staticfiles %} <!-- This area contains all my static files and cdns --> </head> <body> {% include 'inventory/snippets/nav.html' %} {% block content %} {% endblock content %} {% block body %} {% endblock body %} </body> </html> The list of data that is being paginated invoices_list.html {% load filters %} {% load el_pagination_tags %} {% with invoices=invoice_list %} {% paginate invoices %} {% for … -
Best way to render React Components inside HTML templates?
I would like to to use React with Django non Single Page App way - Django will take care of routing, and rendering HTML templates and serving data. React should be used just on some specific components inside HTML page for eg. (dropdowns, autocomplete, modals), ideally being able to just drop for eg. div element with a class inside HTML and pass props for React component. What’s the best - maintainable, scalable solution to go about this ? -
How to follow the DRY principle in django when each view needs to deal with a different model?
I tried to choose a good I have several pages with one form each. I have had to create a view for each of these pages (about 20 different pages), but the code is almost similiar. I don't see any way to cut down on repeating code on this as the different views all have to deal with a different ModelForm instance. Example could would be for one view: def portfolio_dividend_new(request, profile_id): profile = Profile.objects.get(id=profile_id) post_req = False if request.POST: form = DividendForm(request.POST) form.save() post_req = True form = DividendForm() return render(request, 'plan/portfolio/new_dividend.html', {'form': form, 'profile': profile, 'post_req': post_req} ) Example of another view: def portfolio_buyback_new(request, profile_id): profile = Profile.objects.get(id=profile_id) post_req = False if request.POST: form = SharebuybackForm(request.POST) form.save() post_req = True form = SharebuybackForm() return render(request, 'plan/portfolio/new_buyback.html', {'form': form, 'profile': profile, 'post_req': post_req} ) As you can see these views have much of the same code but since they have to instantiate different ModelForm instances I dont see how to keep them from becoming two views. This wouldnt be a problem if it only were two views but its becoming like 20 views which is not maintainable anymore. How can I avoid violating the DRY principle when I have … -
Django 'ProductDetailView' object has no attribute 'user'
Creating a page for an ecommerce site that allows a user to add an item to their cart. Im having issues with no object user found in the ProductDetailView. I overrode the get_context_data function to the class based view, so it will be called when they access the specific product page. Error: 'ProductDetailView' object has no attribute 'user' I'm assuming this is because the view doesn't see users, because it needs a user.objects.all()? views.py from django.shortcuts import render, redirect from django.shortcuts import render from django.views.generic import CreateView, DetailView, ListView, RedirectView, UpdateView from django.views import generic from django.contrib.auth.decorators import login_required # This is to block pages to non users using function views from django.contrib.auth.mixins import LoginRequiredMixin from .forms import ProductForm, ContactForm from .models import Product, Contact from checkout.models import OrderItem, Order from users.models import User, Profile # Create your views here. class ProductDetailView(generic.DetailView): model = Product template_name = 'portal/product_detail.html' def get_context_data(request, **kwargs): filtered_orders = Order.objects.filter(owner=request.user.user_profile, is_ordered=False) current_order_products = [] if filtered_orders.exists(): user_order = filtered_orders[0] user_order_items = user_order.items.all() current_order_products = [product.product for product in user_order_items] context = { 'current_order_products': current_order_products } return context -
redirect to login page if not authenticated from view django rest framework
I am working with django rest framework In one view i want Users only with specific role, that is why i have used this in my view like using authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) But when i try to hit it without login it only show me "403 Forbidden" which is fine, But i also want it to redirect to default django rest framework login page, which is at URL "/api-auth/login" Can anyone help how can i redirect to login is not authenticated. django==2.0 djangorestframework==3.8.2 pyton == 3.4 -
How to return the number of empty fields in an object?
I am trying to create a progress bar feature where it tells you your progress by what data you have inserted into your profile. The idea is that it takes all the fields that are empty and subtracts it from the total number of fields. How do I get all empty fields and return it as a number?