Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to control Python's stdout encoding under Apache/WSGI
I'm writing a Django app, and it prints Unicode to stdout. It works perfectly on the development server, but with Apache and modwsgi I get UnicodeEncodeError: 'ascii' codec can't encode characters .... So, the stdout encoding is forced to ASCII. I've found a number of solutions, all of which seem like they should work according to documentation, but none work for me: I tried setting the PYTHONIOENCODING variable to utf-8, using the SetEnv directive. I also tried setting LANG, LC_ALL, LC_CTYPE to en_US.UTF-8 using SetEnv and PassEnv. Finally, I tried adding lang=en_US.UTF-8 locale=en_US.UTF-8 to the WSGIDaemonProcess directive. The variables are seen in the environment (reflected e.g. on Django error pages in debug mode), but the error still occurs. Why don't these things work and what should I do? Overriding stdout in the code that works fine outside Apache or encoding everything manually doesn't feel like the right approach. Versions: Python 2.7.14, Apache 2.4.29, mod_wsgi 4.5.20 on Arch Linux -
Django Oauth2 Implicit Token Authorization Fail
I've written a chrome extension that uses Chrome's identity API to initiate a webauthflow with a Django Site I have made. Through a button in my extension, I am able to launch and interactive webflow, log into my site (supposedly), and receive an auth token the GET request to my site to receive user information. The main issue here though it that my server is not authenticating according to the profile that has just logged in through the app; it always autheticates to the admin. I am confused about how exactly to use all the different backends, middleware, etc. to get my desired flow: My current settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.BasicAuthentication', 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } AUTHENTICATION_BACKENDS = ( # Uncomment following if you want to access the admin 'oauth2_provider.backends.OAuth2Backend', 'django.contrib.auth.backends.ModelBackend', 'django.contrib.auth.backends.RemoteUserBackend', # '...', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware' ] My Views.py @login_required() def secret_page(request, *args, **kwargs): if request.method == 'GET': receivedurl = request.GET.get('url') print(receivedurl) currentcacheduser = auth.get_user(request) return HttpResponse(currentcacheduser, … -
Ajax powered like button in Django
I have built the next architecture for the like button, but it does not work: models.py class Comentario (models.Model): titulo = models.CharField(max_length=50) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) archivo = models.FileField(upload_to='media/%Y/%m/%d', null=True, blank=True) slug= models.SlugField(default=0) likes = models.ManyToManyField(Perfil, related_name="likes") def __str__(self): return (self.titulo) @property def total_likes(self): return self.likes.count() def save(self, *args, **kwargs): self.slug=slugify(self.titulo) super(Comentario, self).save(*args, **kwargs) views.py try: from django.utils import simplejson as json except ImportError: import json def like (request): if request.method=='POST': perfil=request.user slug=request.POST.get('slug', None) comentario=get_object_or_404(Comentario, slug=slug) if comentario.objects.filter(perfil__id=perfil.id).exists(): comentario.likes.remove(perfil_id) else: comentario.likes.add(perfil_id) context={'likes_count':comentario.total_likes} return HttpResponse(json.dumps(context), content_type='home/json') urls.py url(r'^like/$', login_required(views.like), name='like') .html <input type="button" id="like" name='{{ comentario_slug }}' value="Like" /> <script> $('#like').click(function(){ $.ajax("/home/like/",{ type: "POST", url: "{% url 'home:like' %}", data: {'slug': $(this).attr('titulo'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response) { alert(' likes count is now ' + response.likes_count); }, error: function(rs, e) { alert(rs.responseText); } }); }) </script> When I push the button like it does not do anything. The console tells me: POST htt jquery.min.js:4 p:/127.0.0.1.8000/home/like/404 (not found) and: http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js Which is the problem? thank you for your help -
django - UNIQUE constraint failed: one_file.user_id
I am making a website in which user can upload files and those files are displayed in user's profile. I had displayed a file in user's profile but when I add 2nd file, it gives an error as: IntegrityError at /profile UNIQUE constraint failed: one_file.user_id models.py: class file(models.Model): title = models.CharField(max_length=250) file_type = models.CharField(max_length=12) description = models.TextField(max_length=6000) user = models.OneToOneField(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('one:user') def __str__(self): return self.title views.py: def profile(request): if request.user.is_authenticated(): name= request.user.username form_class = file_form template_name = 'one/profile.html' content = file.objects.all() if request.method=='GET': form = form_class(None) return render(request,template_name,{'form':form,'name':name, 'content':content}) elif request.method=='POST': form = form_class(request.POST) if form.is_valid(): FILE = form.save(commit = False) FILE.user = request.user FILE.save() return HttpResponseRedirect('/profile') tempalte: logged in as: {{name}} <br> <a href="/logout">logout</a> <br> <form method="post" action=""> {% csrf_token %} {% include 'one/form-template.html' %} <button type="submit"> add file </button> </form> <br> <h3>my files</h3> {% for files in content %} <p>{{files.title}}</p> <br> {%endfor%} -
Django - Auto run scripts at certain time on Live Server
Newbie here. I have a lot of different functions in a Python program that downloads a bunch of data from the internet, manipulates it, and displays it to the public. I have bunch of links to different tables of data, and I figure it would be very inconvenient for people to have to wait for the data to download when they clicked the link on my website. How can I configure Django to run the scripts that download the data at say, like 6am? And save some type of cached template of the data so people could quickly view that data for the entire day, and then refresh and update the data for the next day. Your insight and guidance would be very appreciated! Thank you! and Happy holidays! -
Assistance with passing multiple objects via a list to Jsonresponse in Django
I have a code in Django where 5 random numbers are selected and then based on those 5 numbers 5 more queries are made from the database. One this is done I would like to pass all 5 objects from database to the template via json., however I am not sure how to proceed with this. This is what I have now: class multiplePull(TemplateView): template_name = 'gacha/multiplePull.html' def randomStar(self): choice = [5,4,3] probability = [0.1, 0.2, 0.7] star = random.choices(choice, probability) return star[0] def post(self, request): multi = [] characters = [] for x in range(5): star = self.randomStar() multi.append(star) for star in multi: character = Characters.objects.filter(stars=star).order_by('?')[:1] for obj in character: characters.append(obj) return JsonResponse(json.dumps(characters), safe=False) As it is now I get the following error: TypeError: Object of type 'QuerySet' is not JSON serializable How can I do this to make it work? I think I am missing something still but can't really find a solution. This works fine when I simply send this as context data but I don't know how to pass all 5 objects via Json. I would appreciate all help. Thanks you. -
Django Designing Models for Dating App Matches
I’m working on a dating app for a hackathon project. We have a series of questions that users fill out, and then every few days we are going to send suggested matches. If anyone has a good tutorial for these kinds of matching algorithms, it would be very appreciated. One idea is to assign a point value for each question and then to do a def comparison(person_a, person_b) function where you iterate through these questions, and where there’s a common answer, you add in a point. So the higher the score, the better the match. I understand this so far, but I’m struggling to see how to save this data in the database. In python, I could take each user and then iterate through all the other users with this comparison function and make a dictionary for each person that lists all the other users and a score for them. And then to suggest matches, I iterate through the dictionary list and if that person hasn’t been matched up already with that person, then make a match. person1_dictionary_of_matches = {‘person2’: 3, ‘person3’: 5, ‘person4’: 10, ‘person5’: 12, ‘person6’: 2,……,‘person200’:10} person_1_list_of_prior_matches = [‘person3’, 'person4'] I'm struggling on how to represent this … -
How to filter the options for a ForeignKey based on an other ForeignKey
I need to filter the options for a ForeignKey based on an other ForeignKey. class LabValue(models.Model): measurement = models.ForeignKey( 'LabMeasurement', on_delete=models.CASCADE) unit = models.ForeignKey( LabMeasurementUnit, on_delete=models.CASCADE, limit_choices_to={'parameter__id': self.measurement.parameter.id}, ) How can I retrieve self.measurement.parameter.id? If I manually enter an ID like for example "1" the query works. -
Designing code for proper error handling in a Django / Python app?
I'm in the midst of building a Django app and am hoping to get some advice on the proper way to handle errors and bugs in my code. Here's a common situation exemplary of the problems I have: a user purchases a product. To process the purchase, my views need to perform a number of actions: First, the view should create a User object in the database. If that is successful, the view should create an Order object and assign it to the newly-created User. If that is successful, my code should create a Product object and add it to the newly created Order. This is all well and good when no errors occur - but I find that the occasional error is inevitable in my code, and I want my app to deal with errors gracefully, rather than crashing outright. For example, if, for any reason, an Order object cannot be created, the view should show the user an error and remove the User object that was previously created. And, it should throw a graceful error message rather than crashing outright and serving the user a Http 500 error. The only way I can think of to do this … -
model messages on django
I create model for messages , user can have many read messages. Message can read many users. Is similar to group chat in slack. class Message(models.Model): user = models.ForeignKey(User) users_read = models.ManyToManyField(User, related_name='read_messages') date_created=models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=500) Right i make references in my models? sorry for my english, i learning him -
What are the benefit of Python Django?
I would like to know some of the benefits of using Python Django? This can include security features, ease of use or any other aspect that make Django stand out.