Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MySQL trigger condition
Consider the following scenario where users can enable/disable MySQL triggers using a web interface. I am creating a session variable once the user opens a specific web page by executing the following command: SET @vsAge = 0 This variable is then used inside a BEFORE INSERT trigger: BEGIN IF (@vsAge = 1) THEN IF new.age < 0 THEN SET new.age = 0; END IF; END IF; END However when I run my Django server and create this variable, my trigger doesn't work properly, running the command SELECT * FROM performance_schema.user_variables_by_thread is showing me that this variable does exist, and the problem can't be with the code since if I create this variable using MySQL workbench, everything works fine, so the problem is probably somewhere on the server. How does django handle database connections and sessions, I'm guessing somewhere in my code the database connection gets closed and this variable is stored in a different session. Is it possible to force django to use a single MySQL session? I use the django database api for some operations and for making variables I am using: class Database: def __init__(self): self.con = None def connect(self): self.con = mdb.connect('localhost', 'root', 'password', 'dbname') def trigger_toggle(self, … -
How to manage PK when a view must be called with it
Hi guys I have an issue with my private keys. I do not know what is the problem if someone could give me a hand it would be greatly appreciated. the errror that I get is : Generic detail view ProjectDetailView must be called with either an object pk or a slug my models are the following: class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) members = models.ManyToManyField(MyUser, related_name="members") def __str__(self): return self.team_name class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True) candidat_answers = models.ManyToManyField('survey.response') def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs = {'pk1' : self.pk}) def __str__(self): return self.name my views : class HomePage(TemplateView): template_name= 'index.html' class LinkTeam(generic.ListView): template_name = 'link_project.html' def get_queryset(self): #import pdb; pdb.set_trace() #team2 = Team.objects.all().filter(team_hr_admin = self.request.user) queryset = Team.objects.filter(team_hr_admin=self.request.user) return queryset def TeamSelect(request): import pdb; pdb.set_trace() if request.method == "POST": select_form = EditSelectTeam(request.user, request.POST) if select_form.is_valid(): data = select_form.cleaned_data['team_choice'] obj2 = Project.objects.filter(project_hr_admin=request.user) obj3 = obj2.latest('id') if obj3.team_id == None: obj3.team_id = data obj3.save() obj4 = obj3.team_id obj5 = obj4.members.all() for i in obj5: current_site = get_current_site(request) message = render_to_string('acc_join_email.html', { 'user': i.first_name, 'domain':current_site.domain, }) mail_subject = 'You have been invited to SoftScores.com please LogIn to … -
Django: How to trigger a session 'save' of form data when clicking a non-submit link
I know if want you to store form information to the session during a submit you do it with the 'def post' in your view. However, I can not figure out how to store form information when a random link e.g. 'homepage'. How would you go about storing form information when a user clicks away from the form? -
signupp() got an unexpected keyword argument 'name'
Here is my views.py Here is my models.pyenter image description here -
Passing kwargs to django admin form
I have a couple of models, for example: class Product (models.Model): title = models.CharField( max_length = 255, ) supplier = models.ForeignKey( Supplier, blank=True, null=True ) min_level = models.IntegerField( default = 10, ) quantity = models.IntegerField( default = 0 ) class ReOrder (models.Model): product = models.ForeignKey( Product, ) order_quantity = models.IntegerField( default = 0 ) order_date = models.DateField( default = datetime.datetime.now() ) received = models.BooleanField( default = False ) def __unicode__(self): return u'%s' % (self.product) When I'm listing my Products within Django Admin I have a ReOrder button. When click I want to go straight to the Django Admin ReOrder Add ReOrder.product defaulting to the Product prefilled Getting the button etc in place is fine but I cannot work out how to pass the Product.id through. I'm trying: reverse('admin:inventory_reorder_add', kwargs={'product_id' : obj.pk }) where obj.pk is the Product. This is giving me Reverse for 'inventory_reorder_add' with keyword arguments '{'product_id': 31L}' not found How do I make a call and have the field pre-selected within admin? Thanks for your help. Below is the complete ProductAdmin class. class ProductAdmin(admin.ModelAdmin): list_display = ['title', 'get_sku', 'get_ebaylink', 'quantity', 'quantity_status','account_actions','weekly_stock','monthly_stock','quarterly_stock'] ordering = ['title', 'quantity', ] inlines = [SkuInline, EbayLinkInline] search_fields = ('title', 'sku__sku', 'ebaylink__custom_label', ) fields = … -
Django: Query Selected Info in Model Within Class Based Views
I created some link with model-slug. But When I click my link, go to the page but return the empty value. I want to When I click any link, It will query value from the selected field like class_name or slug field. this class list html page {% extends "result/base.html" %} {% block title %}Class List Name{% endblock title %} {% block content %} <div class="row"> <div class="col-md-12 col-xs-offset-4"> <h2>Class List</h2> {% for object in object_list %} <a href="{% url 'result:class-detail' object.slug %}">{{object.class_name}}</a> {% endfor %} </div> </div> {% endblock %} this is models.py file class ClassName(models.Model): class_name=models.CharField('Class Name', max_length=10) class_added=models.DateTimeField(auto_now_add=True) class_updated=models.DateTimeField(auto_now=True) slug=models.SlugField(max_length=200, unique=True) def __str__(self): return self.class_name this is views.py file class ClassListView(ListView): model=ClassName slug_field = 'slug' template_name='result/class_list.html' class ClassDetailView(DetailView): model=ClassName slug_field = 'slug' template_name='result/class_detail.html' def get_context_data(self,*args, **kwargs): context = super(ClassDetailView, self).get_context_data(*args,**kwargs) context['class_wise_std'] = StudentInfo.objects.filter( student_class_name__class_name__startswith=self.model.slug) return context this is class details html page {% extends "result/base.html" %} {% block title %}Class Detail's List{% endblock title %} {% block content %} <div class="row"> {% for object in class_wise_std %} <div class="col-lg-12 col-sm-offset-4" style="margin:20px 10px"> <p>Name: {{object.student_name}}</p> <p>Class: {{object.student_class_name}}</p> <p>Father's Name: {{object.student_father_name}}</p> <p>Mother's Name: {{object.student_mother_name}}</p> <p>Roll: {{object.student_roll}}</p> </div> {% endfor %} </div> {% endblock content %} this code def get_context_data(self,*args, … -
What are the best possible ways to integrate a Front End(Vue) and Backend(Django-DRF) for a web application?
What are the best possible ways to integrate a Front End(Vue) and Backend(Django-DRF) for a web application ? -
Is it possible to read the SECRET KEY from djano settings.py by other apps?
I want to use the django SECRETE_KEY for creating my JWT (Json web token). Is it possible to read the django secrete key from all apps under a django project? Please advise me on if it is a good practice to use the django secrete key for internal app logic. -
changing VS2015 django project settings directory name cause ModuleNotFoundError on startup
I use VS2015 create a Django project. It has the project directory (say, MySite). Under which, it also has a directory with the same name (i.e. MySite) which contains web project configuration and setting files such as settings and urls. I don't like it having the same name as the project root directory and so changed this settings directory name to 'config'. I also made the following changes: 1. in manage.py: os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "config.settings" ) 2. in IDE's Projects setting, remove $(MSBuildProjectName) from Django's "Settings Module". However, when I start the project from IDE debugging run, execute_from_command_line(sys.argv) in manage.py raises an exception ModuleNotFoundError on 'MySite'. It seems that Django startup hardwired the sys.argv value to the project name. That is, it assumes that the settings.py is in a subdirectory with the same name as project name. How can I change this default behaviour so that it understands the settings in the directory with a different name. Thank you -
Django build video website similar to YouTube
I am trying to build a video upload website using Django 1.11.8, Python 3.6.3 and MySQL. I have No experience in developing any kind of video upload website. But I am confident that I can build similar website with my Django experience. I am worried about the performance and scalability. I want to share my approach and please correct me If I am wrong or you can suggest me better way. I already have default user database on Django.contrib.auth.model>>User and will be use same users information to upload, likes, views and other interactions with videos 01. Create Model.py (this is sample) from django.db import models from django.contrib.auth.models import User class Channel(models.Model): name = models.CharField(max_length=100) subscribers = models.ManyToManyField(User, related_name='+', blank=True) creation_time = models.DateTimeField(auto_now_add=True) modified_time = models.DateTimeField(auto_now=True) class Subscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') channel = models.ForeignKey(Channel, on_delete=models.CASCADE) notifications = models.BooleanField(default=True) class Playlist(models.Model): video = models.ForeignKey('Video', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class Category(models.Model): name = models.CharField(max_length=100) class ChannelSettings(models.Model): channel = models.ForeignKey(Channel, on_delete=models.CASCADE) verified = models.BooleanField(default=False) 02 Create View.py To render Html templates frames. such as video view page, channel page, playlist page, history page, search page I will not use Django template tags to populate any information. 03 Create api.py To create … -
Javascript add class to classList don't add. Used in Django web development framework
We have a form in which we want all input areas with faulty submitted data to gain red borders. This is done by setting the class of the input tag to "form-control-danger" in addition to the original class "form-control". The HTML/JS/Django code looks like this, and it is mostly correct. I have controlled that the scripts tags are only generated and run when faulty data is submitted. <!-- Output all fields --> {% for field in form %} <div class="input-group form-group-no-border"> <span class="input-group-addon"> <i class="now-ui-icons {% if field.name == 'email' %} ui-1_email-85{% endif %} {% if field.name == 'username' %} users_circle-08{% endif %} {% if field.name == 'password1' %} ui-1_lock-circle-open{% endif %} {% if field.name == 'password2' %} ui-1_lock-circle-open{% endif %} "></i> </span> {{ field }} <!-- Give input box red border if data is not valid --> {% if field.errors %} <script> var element = document.getElementById("{{ field.id_for_label }}"); element.classList.add("form-control-danger"); </script> {% endif %} </div> {% endfor %} As we feed the form faulty data this gives us this source code. <div class="input-group form-group-no-border"> <span class="input-group-addon"> <i class="now-ui-icons ui-1_lock-circle-open "></i> </span> <input type="password" name="password2" value="iuhqeifuhweifuhweifuwefw" id="id_password2" required placeholder="Password again..." class="form-control" /> <!-- Give input box red border if data is … -
Already registed user name can be registed
Already registed user name can be registed in user creation form.Im making Django application. I wrote in views.py def regist(request): regist_form = RegisterForm(request.POST or None) context = { 'regist_form': regist_form, } return render(request, 'registration/regist.html', context) def regist_save(request): regist_form = RegisterForm(request.POST or None) if request.method == "POST" and regist_form.is_valid(): regist = regist_form.save(commit=False) regist.is_staff = True regist.save() advertisements = Advertisement.objects.all() return render(request, 'registration/detail.html', {'advertisements': advertisements}) in regist.html <form class="form-horizontal" action="/accounts/regist_save/" method="POST"> <div class="form-group-lg"> <label for="id_username">Username</label> {{ regist_form.username }} <p class="help-block">{{ regist_form.username.help_text }}</p> </div> <div class="form-group-lg"> <label for="id_email">Email</label> {{ regist_form.email }} <p class="help-block">{{ regist_form.email.help_text }}</p> </div> <div class="form-group-lg"> <label for="id_password">Password</label> {{ regist_form.password1 }} <p class="help-block">{{ regist_form.password1.help_text }}</p> </div> <div class="form-group-lg"> <label for="id_password">Password(Conformation)</label> {{ regist_form.password2 }} <p class="help-block">{{ regist_form.password2.help_text }}</p> </div> <div class="form-group-lg"> <div class="col-xs-offset-2"> <button type="submit" class="btn-lg regist">Register</button> <input name="next" type="hidden" /> </div> </div> {% csrf_token %} </form> Now in this user registration form, if I write already registed user name&email&password,these data is not registed but detail.html is load.I wanna show alert if I do so like "this user name is already registed".Why isn't my web page not my ideal one?Why can I resist already registed user name in my site?How should I fix this? -
How to dynamically route category urls in Django
Let's say I've a Blog, which has posts, each of which has, potentially, many categories. I would want to display category pages on my blog, such that going to myblog.com/category-1/ would correctly route to a myblogapp/views.py/category-indexfunction that would, in turn, return a category-index.html template with a display of posts with category-1 assigned to them. What's the best practice for approaching this? -
django remove all products from a cart
I'm using [django-carton][1] [1]: https://github.com/lazybird/django-carton to add cart functionality to my products app. I have the ability to add and remove products to and from the cart, as well as show the cart contents. I'm trying to work out how to empty the cart. Here's the views.py: def add(request): cart = Cart(request.session) product = Product.objects.get(id=request.GET.get('id')) cart.add(product, price=product.price) return redirect('shopping-cart-show') def remove(request): cart = Cart(request.session) product = Product.objects.get(id=request.GET.get('id')) cart.remove(product) return redirect('shopping-cart-show') def show(request): return render(request, 'shopping/show-cart.html') ...and here's how I'm displaying the products on the cart page: {% for item in cart.items %} <div class="col-md-6"> <a href="/{{item.product.id}}/">{{ item.product }}</a> </div> <div class="col-md-2"> <p>{{ item.quantity }}</p> </div> <div class="col-md-2"> <p>${{ item.subtotal }}</p> </div> <div class="col-md-2"> <a href="/shopping-cart/remove/?id={{ item.product.id }}" class="btn btn-sm btn-product">Remove</a> </div> {% endfor %} I've tried a few different ways to clear the cart. I assigned {{cart.clear}} to a button but this also clears the page on refresh, whereas I'm trying to clear the page on clicking the button only. I was hoping to do this without Java Script but I'm struggling to find a way. All help gratefully received. -
Way to change default times in Django time popup
Is there a way to add to or change the default times in the default DateTime widget in the Django admin? See attached image for reference. I'm looking to add/change where it says "Choose a time". -
django url.py error page not found
I can't make url.py. It still shows page not found. This is my url. /pins/tag/?search=A/ /pins/tag/?search=B/ /pins/tag/?search=C/ A,B,C is variable strings. This is my url.py url(r'^pins/tag/?search=(?P<tag>(\w|-)+)/$') But, it is wrong. How I make a correct url.py? -
Deleting objects in core data depending on JSON in Python
I'm having troubles deleting database records that aren't in the JSON I get daily from an API. Context: I'm using an API to add release dates to my database in django. If this release date doesn't exist but exists in the json; add it in, if it exists in both update it, but now how do I delete the release date if it exists in my databse but no longer exists in the new JSON? Thank you, here's what I have so far: for release_date_object in game_object['release_dates']: release_date = ReleaseDate.objects.filter(game=game.id, platform=release_date_object['platform'], region=release_date_object['region']) # (if) a release date of this platform, region and game already exists, update the 'dynamic' data # like date, human, m and y and then continue through the loop if release_date.exists(): if 'category' in release_date_object: release_date.category = release_date_object['category'] if 'date' in release_date_object: release_date.date = release_date_object['date'] if 'y' in release_date_object: release_date.y = release_date_object['y'] if 'm' in release_date_object: release_date.m = release_date_object['m'] if 'human' in release_date_object: release_date.human = release_date_object['human'] # update: filter returns a queryset. A queryset isn't a single object for r_object in release_date: r_object.save() # update continue # important elif not release_date.exists(): # (else) adds the release date or delete it because it no longer exists in the … -
Django - list_display attribute not showing any fields for Model with OneToOne with User Model
So I have come an across something sort of weird. I just noticed that none of my fields that I want displayed on my admin page is not there. The failing model is a "Profile" model that is an extension to the User model, with a oneToOne relationship The code looks something like this. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. #We need to extend the User Model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=4096, null=True) email_confirmed = models.BooleanField(default=False) def __str__(self): return self.user.username def get_username(self): return self.user.username def get_bio(self): return self.bio def get_email_confirmed(self): return self.email_confirmed @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() admin.py from django.contrib import admin from .models import Profile # Register your models here. class ProfileAdmin(admin.ModelAdmin): list_display = ('email_confirmed', 'bio') admin.site.register(Profile) However, even with these changes, the admin page looks like this: Merry Christmas :D -
Multipe filters on exists
Hi I'm trying to filter my exists query set into looking through 3 fields to check if a release date of this game, platform and region already exists. What I seek to accomplish: if ReleaseDate.objects.filter(game=game.id).filter(platform=release_date_object['platform']).filter(region=release_date_object['region']).exists(): Thank you. -
Get first object of query-set in Django templates
I understand that Django separates data and presentation such that Object.filter(id=value).all() isn't possible through templates. What I'm struggling to understand is the best practice for achieving this same type of end result. For example, in one of my apps I've data for products, which include some one-to-many relationships with images. That's to say, one product may have many images. in my AppName/views.py file, I've got the following: def index(request): response = render_to_response('AppName/index.html', context={ 'products': Product.objects.all(), }) return response in my AppName/templates/AppName/index.html file, there's a section with the following: {% for product in products %} <li>{{ product.name }}: ${{ product.price }}</li> {% endfor %} What I'd like to be able to do, is include the equivalent of {{product.images.first().url}} in the mix. What's the typical approach for this? -
Recover database after ran heroku pg:reset DATABASE
I accidently ran this command and it seems like I've lost all my database. $heroku pg:reset DATABASE Is there anyway I can recover my database... I truly appreciate your help in resolving the problem!! -
Getting 404 error messages after placing Django Python app in Docker Container
I am trying to get some template information to display on a web page served in from a Docker container. It is using uWSGI. The name of the template is base.html There are "decorations" associated with the base.html file that are located in the static directory. To be more specific, it resides in the static/wforms/assets directory. Below is how the assets directory is being used in the template. <link href="{% static 'wforms/assets/global/plugins/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css" /> <link href="{% static 'wforms/assets/global/plugins/simple-line-icons/simple-line-icons.min.css' %}" rel="stylesheet" type="text/css" /> <link href="{% static 'wforms/assets/global/plugins/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet" type="text/css" /> Whenever I go to a page that uses the base.html template, the decorations are not found and the resulting web page is a mess. Everything works fine in PyCharm. The problem happens when moving everything to the directory structure in a Docker Container. Below is the directory structure in PyCharm. I start the container like this: docker run -it --rm -p 8888:8888 -v /home/dockcclubdjango/apps/wforms/assets:/code/backendworkproj/static/wforms/assets --name my-running-app my-python-app As an FYI, the /home/dockcclubdjango/apps/wforms/assets does exist and has the correct info in it. Then, I attempt to go to the web home page. The page shows up but all of the "decorations" are not present. So, the page looks somewhat … -
Can't download Django throught terminal
I am trying to download and install Django through the terminal but for some reason, I keep getting an error. I ran the command "sudo pip install Django". This is what is printed out in the terminal. Collecting Django Downloading Django-2.0.tar.gz (8.0MB) 100% |████████████████████████████████| 8.0MB 121kB/s Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/tmp/pip-build-Y1GrsP/Django/setup.py", line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-Y1GrsP/Django/ -
Can't parse a static JSON file in Django 1.8
I have the following tree: myDjangoSite/ ... myApp/ ... static/ ... myApp/ myData.json And I have this view.py file: import json from django.shortcuts import render from django.contrib.staticfiles.templatetags.staticfiles import static url = static('myApp/myData.json') json_data = open(url) def helloWorld(request): return render(request, 'myApp/index.html') ...and when I access to the webpage, the browsers shows this message: IOError at / [Errno 2] No such file or directory: '/static/myApp/myData.json' I don't understand why it says "no such file or directory", if the file DOES exist and how to solve it. -
Django form fields as template variables
The main question is if it is possible to specifify specific form fields at different given locations in your html template in any smooth way. e.g. {{ form.password }} However, that does not seem to work. (I swear that I have seen this somewhere, but I just can't find it anymore on the internet) My view for signing up new users is inheriting from UserCreationForm and looks kind of like this: views.py def signup(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'core/authentication/registration_form.html', {'form': form}) It sends this form straight to the template registration_form.html, this is how I wish it worked: <form class="form" method="POST" action=""> <div class="card-body"> <div class="input-group form-group-no-border"> <span class="input-group-addon"> <i class="now-ui-icons users_circle-08"></i> </span> {{ form.first_name }} </div> </div> This is how it actually works (for now): <form class="form" method="POST" action=""> <div class="card-body"> <div class="input-group form-group-no-border"> <span class="input-group-addon"> <i class="now-ui-icons users_circle-08"></i> </span> <input type="text" class="form-control" placeholder="First Name..."> </div> </div> This might be a stupid question, but oh well I am curious. Thank you in advance