Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use apps with the same name in django
I created a project say foo. And created an app named admin. But it causes an error django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: admin” So I read this and made changes as mentioned there. I marked the label as foo.admin. I don't exactly know what the label is, but maybe this is the unique name given to an app to distinguish apps with the same name in case. So is that mean, everywhere I have to use label instead of name? But it causes another error. String model references must be of the form 'app_label.ModelName'. So I used the name in models as foo.admin in ForeignKey parameter. But the same error comes up. But the error persists. I googled the error and found this. So I changed the ForeignKey parameter from foo.admin to admin. But in either case, I'm having this error. So in short I want to ask How to use apps with the same name in the same django project, like Which files are need to be modified and what to write ForeignKey parameters etc.? (I'm using django 2.0) -
Unable to use variables from other app models after importing Django
I'm having a rather odd issue that boils down to a lack of understanding rather than an actual problem with the code. What I mean when I write that should become more clear a bit later on. This will be a little long so jump ship now if you don't have a lot of time. I'm attempting to get it so that I can use variables/what from my understanding is a database across different Django apps in my project. The code I'm having an issue with is the following: (This is from the posts models) from django.conf import settings from django.db import models from django.urls import reverse class Post(***): message = *** date = *** author = ***** https://pastebin.com/gGyYXG4q This code actually works fine, in the posts app in the template post_list. I need it to work in a different app altogether. Logically I simply copied that code over, which failed immediately. After doing a small amount of digging I managed to figure out that I needed to import the models of posts into the app I'm trying to get this to work in. After I did that I expected this to work, but for some obvious reason I am … -
Membership and Ownership in Django
I've recently begun learning Django using some tutorials and I'm working on a little project to learn more. I'm trying to create a model in Django (2.0) named 'Course'. Each course is created by one of the users (there's no user type or anything, anyone can create a course) known as the instructor. The instructor can add other users (using their usernames) as assistants. Finally, there are normal users who can enroll in the courses. I checked Django's documentation and came across three types of relationship; One to One, Many to One, and Many to Many. I wanted to use one to one, one to many and many to many, for the instructor, assistants, and students respectively. Am I on the right track? Or should I implement membership and ownership another way?! -
permission duplicate key value violates unique constraint "auth_permission_content_type_id_codename Key (content_type_id, codename) already exists
i had 5 permission class Meta: permissions = ((“can_go_in_non_ac_bus”, “To provide non-AC Busfacility”), (“can_go_in_ac_bus”, “To provide AC-Bus facility”), (“can_stay_ac-room”, “To provide staying at AC room”), (“can_stay_ac-room”, “To provide staying at Non-AC room”), (“can_go_dehradoon”, “Trip to Dehradoon”)), now below i have 6 permissions class Meta: permissions = ((“can_go_in_non_ac_bus”, “To provide non-AC Bus facility”), (“can_go_in_ac_bus”, “To provide AC-Bus facility”), (“can_stay_ac-room”, “To provide staying at AC room”), (“can_stay_ac-room”, “To provide staying at Non-AC room”), (“can_go_dehradoon”, “Trip to Dehradoon”), (“can_go_delhi”, “Trip to Delhi”) and i updated the model, as of now new user getting 6 permissions but old user getting 5 permissions now i need to write a script to add 6th permissions to old user? ct =ContentType.objects.get_for_model(old_user) permission = Permission.objects.create(codename =’can_go_delhi’,name=’Trip to Delhi’, content_type = ct) old_user.user_permissions.add(permission) but i am getting error like this ==> ('duplicate key value violates unique constraint "auth_permission_content_type_id_codename_key"\nDETAIL: Key (content_type_id, codename)=(82, can_go_delhi) already exists.\n',) then i changed to Permission.objects.get_or_create now error is ==>"int() argument must be a string or a number, not 'Permission'",) so how to write script? please -
Is it possible to write simple web application using python without using frameworks like flask or Django
I am a php developer, I want to write simple python web application without using framework like flask or django. In php i can build a web application without using frameworks like codeigniter/laravel(php frameworks). I use apache web server with php, can i use apache web server with python or is there any other web server needed for python? -
Django and embeding videos using parsing to get the youtube video id
I feel like i am very close to making it work. i tired everything but the videos don't show. the problem is in the HTML i think. Models: class Video(models.Model): link = models.URLField() def video_id(link): query = urlparse(link) if query.hostname == 'youtu.be': return query.path[1:] if query.hostname in ('www.youtube.com', 'youtube.com'): if query.path == '/watch': p = parse_qs(query.query) return p['v'][0] if query.path[:7] == '/embed/': return query.path.split('/')[2] if query.path[:3] == '/v/': return query.path.split('/')[2] def __unicode__(self): return self.link views: def index(request): full_list = Video.objects.all() return render_to_response('index.html', {'full_list': full_list}) HTML: {%load staticfiles %} {%load static%} <h1>YouTube list</h1> {% if full_list %} <ul> {% for video in full_list %} <li> <iframe width="560" height="345" src="{{Video.video_id}}?rel=0" frameborder="0" allowfullscreen></iframe> </li> {% endfor %} </ul> {% endif %} i have been at it for three days now and i can't seem to make the videos appear. -
request.GET.get() returning "None"
I really don't know what is happening. The request.GET.get() works totally fine to add to the DB for estate_owned. Now after "for estate in estates" it just returns "None". It's the same code, am I missing something? I'm new to Django, sorry! views.py class CreateView2(TemplateView): template_name = 'estate_form2.html' template2 = 'match.html' model = Estate def get(self, request): estates = Estate.objects.all() estate_owned = estates.order_by('-pk')[0] estate_owned.wished_price_by_owner = request.GET.get('wished_price_by_owner') ** WORKS FINE!!! ** estate_owned.save() for estate in estates: estate.points = 0 if estate.price <= 1.1 * int(request.GET.get('wished_price_by_owner', 0)): **request.GET.get RETURNS NONE!!** estate.points += 11 Thanks a lot! -
Django ORM: DateField filtering __gte result SQL is not valid
I am working on projects in Django. Even if I filter with Django ORM, the entire row is being returned. When I entered the query generated by ORM directly into psql, the condition to be interpreted as datetime.date was interpreted as an integer. class Memo(models.Model): contents = models.CharField('Memo Contents', max_length=255) remind_date = models.DateField('Remind Date', db_index=True) class Meta: ordering = ('-remind_date', ) print(Memo.objects.filter(remind_date__gte=datetime.date(2018, 3, 20)).query) # SELECT "memo_memo"."id", "memo_memo"."contents", "memo_memo"."remind_date" # WHERE "memo_memo"."remind_date" >= 2018-03-20 # ORDER BY "memo_memo"."remind_date" DESC psql error : ERROR: operator does not exist: date >= integer LINE 1: ...memo_memo"."remind_date" >= 2018-03... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. So, Django ORM is doing wrong thing? What's happening?? Django : 1.11.9 PostgreSQL : 10.1 OS : macOS High Sierra 10.13.3 -
AttributeError: 'Manager' object has no attribute 'order_py'
I am getting an error mentioned in title when I run the local_host_server/topics from django.shortcuts import render from .models import Topic Create your views here. def index(request): """The home page for learning log""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics""" topics = Topic.objects.order_py('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) how can I resolve the order_py issue in Django. -
How do I update an entry while using @detail_route?
How do I update a model when using @detail_route? See code below which is working for POST but not for PATCH. If I send in a PATCH request it creates a new entry i.e. it posts. class Company(models.Model): title = models.CharField(max_length=50) type = models.CharField(max_length=3) class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('id', 'title', 'type') class CompanyViewSet(viewsets.ModelViewSet): queryset = Company.objects.all() serializer_class = CompanySerializer filter_fields = ('id', 'type',) def get_serializer_class(self, data=None, request=None): return CompanySerializer(data=data, context={'request': self.request}, partial=True) @detail_route(methods=['post', 'patch'], url_path='private') def private_company(self, request, version, pk=None): serializer = self.get_serializer_class(request.data, self.request) serializer.is_valid(request) serializer.save() return Response(data=serializer.data, status=status.HTTP_201_CREATED) # <<== What do I need to do an update? -
Delegating attributes to those of a OneToOneField in Django
I have a model UserGuide which extends Django's User model through a one-to-one relationship. I would like to make it such that for an instance lucy_guide, a call to an attribute lucy_guide.first_name will return luyy_guide.user.first_name (and similar for last_name). Here is my first pass at implementing this: class LucyGuide(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __getattr__(self, attr): if attr in ['first_name', 'last_name'] and self.user: return getattr(self.user, attr) return super().__getattr__(attr) Does this look OK? I know Django can behave differently from 'regular Python' due to its use of metaclasses. -
Django website failing when using os.einviron.get for aws keys
I am using django, aws and heroku. I have a website that goes live locally when I have the following ids set. AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID","aaaa") AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY","bbbb") However, this is bad form because I can't commit this file to gitlab. If I did, my keys would be public (my gitlab repo isn't private yet, still practicing before I make that commitment) and all hell breaks loose. However, if I use the following code and try to go live locally AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") I get the following error: botocore.exceptions.NoCredentialsError: Unable to locate credentials When I use the latter code and go live via heroku as an actual webpage it works. It's as if my os.environ.get command doesn't work in my local settings. Does anyone konw what to do? I'd hate to have to change these lines of code everytime I want to commit to git or push to heroku. I feel like the 2nd code should work locally, but I don't see how. -
Using Ajax to send form data to Django view
I want to use selected value from the template to filter data in months but keep getting 403 (Forbidden) error. Here are my files: Models.py class FuelOperation(models.Model): date = models.DateField(default=datetime.date.today) liter = models.IntegerField() Template.html <form id="month-form" method="post"> {% csrf_token %} <select id="month-select" class="selectpicker"> <option value="03" name="March">3</option> <option value="04" name="April">4</option> </select> </form> Javascript $("#month-select").on("change", function(){ var selectedValue = $(this).text(); $.ajax({ url : "{% url 'index' %}", type : "POST", data : {"value" : selectedValue}, dataType : "json", success : function(){ } }); }); views.py def index(request): if request.method == 'POST': key = request.POST.get('value') operations = FuelOperation.objects.filter(date__month=key) context = {'operations': operations} return HttpResponse(simplejson.dumps({"success": "true"}, mimetype="application/json")) return render(request, 'fuel/index.html', context) urls.py path('', views.index, name='index'), -
Validation for dynamic radio buttons
I want to know how to check if a radio button has been selected before the user clicks submit. At the moment it allows a submission if nothing has been selected. remove.html {%for laptop in laptops%} <form action = "{%url 'laptops:delete'%}" method = "post" enctype="multipart/form-data"> {% csrf_token %} <div class="radio"> <input type="radio" id = "laptop_{{laptop.id}}" name="laptopname" value = "{{laptop.id}}"> <label for = "laptop_{{laptop.id}}">{{laptop}}</label> </div> {%endfor%} <input type="submit" value="Submit" id="delete-button"/> </form> views.py #Gets id value from the 'laptopname' radio button laptopid = int(request.POST.get('laptopname')) #Finds matching id value laptop = Laptop.objects.get(id=laptopid) #Populates form with matching data data = {'Name': laptop.Name, 'specification': laptop.specification,'warranty': laptop.warranty, 'condition':laptop.condition} form = forms.MakeSale(initial=data) return render(request, 'laptops/laptop_sale.html', {'form': form}) Is my approach wrong? Should I be doing the validation using a form for the radio buttons instead? -
Cannot run one-off process at this time message on Heroku (DJango)
After setting up Heroku with DJango, I tried to use the following command: heroku run manage.py This resulted in "Cannot run one-off process at this time. Please try again later". Do I just have to try again later? Or does it require some action on my part? Thanks! -
How to capture the result returned by a callback function call on a Bokeh TextInput widget?
I'm working on a Bokeh application which, among other widgets, has a TextInput and a MultiSelect. (Since Bokeh does not have a native Search widget, I try to build one that has a box for input and a box to display the results returned by a dB query based on the input field.) The code for TextInput box is ask_fruit and MultiSelect is used to display the results returned by dB query. The callback function used by TextInput is db_query. def SearchDisplay(): ask_fruit = TextInput(value="Enter fruit name here", title="Input box:" ) ask_fruit.on_change("value", db_query) available_fruits = MultiSelect(title=None, value=["All"], options=[] ) return [ask_fruit, available_fruits] def db_query(attr, old, new): conn = pyodbc.connect('fruit-db', autocommit=True) curs = conn.cursor() query = "select fruit_id from fruitdB" curs.execute(query) fruit_list = curs.fetchall() return fruit_list The question is how to populate the MultiSelect widget with results returned by the callback? Is it possible to just do options=[ask_fruit.on_change("value", db_query)] in code for MultiSelect? The action would look like this: -
Uploading multiple files in Django 2.0
I really spend the two last days on searching how to upload single file in Django 2.0 and after achieving it, here I'm in front of "Uploading Multiple Files", the documentation isn't enough, I searched many time without any result. Here is my code: models.py: from django.db import models class Image(models.Model): title = models.CharField(max_length=40) image = models.ImageField() def __str__(self): return "{0} => {1}".format(self.id, self.title) forms.py: from django import forms from . import models class Image_Form(forms.ModelForm): class Meta: model = models.Image fields = "__all__" widgets = { "title": forms.TextInput( attrs={ "required": "True", "autofocus": "True", } ), "image": forms.FileInput(attrs={'multiple': True}), } views.py: from django.shortcuts import render, redirect from . import models, forms from django.views.generic.edit import FormView def index(request): all_images = models.Image.objects.all() image_form = forms.Image_Form() upload_files = Upload_Files() dico = { "images_key": all_images, "form_key": image_form, "upload_key": upload_files, } return render(request, "index.html", dico) def media_upload(request): if request.method=="POST": upload_files = Upload_Files() upload_files.post(request) else: return redirect("index") class Upload_Files(FormView): form_class = forms.Image_Form template_name="index.html" success_url = '/index/' def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('image') if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) index.html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <title>index page</title> </head> <body> <form method="POST" action="{% url 'media_upload' %}" enctype="multipart/form-data"> {% csrf_token … -
Filtering many-to-one in Django template
Let's say I have these models: class Profile(models.Model): headline = models.CharField(max_length=200) class ProfilePhoto(models.Model): photo = models.ImageField(upload_to='profiles/photos') owner = models.ForeignKey(Profile, related_name='photos', on_delete=models.CASCADE) type_choices = ( ('PR', 'Primary'), ('AD', 'Additional'), ) type = models.CharField(max_length=2, choices=type_choices, default='AD') and the following view: def profiles(request): # Retieve all active profiles profiles = Profile.objects.filter(status='AC').order_by('-updated_at')#.filter(photos__) context = {'profiles': profiles} return render(request, 'profiles.html', context) and this in my template file: {% for profile in profiles %} <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <div class="panel panel-default"> <div class="panel-body"> <p><a href="{{ profile.get_absolute_url }}">{{ profile.headline }}</a></p> <img src="{{ MEDIA_URL }}profiles/thumbs/{{ profile.photos.first.photo }}"> </div> </div> </div> {% endfor %} Here I get one photo for each profile because of profile.photos.first.photo in the template but what I want instead is to select a single photo for each profile with the condition that it has a type of 'PR'. Any help would be appreciated. -
Django IntegrityError changing a ForeignKey
I have a model LucyGuide which extends Django's User model through a OneToOneField: class LucyGuide(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) There is also a Company model which has a field called lucy_guide which is a ForeignKey to the User model: class Company(models.Model): lucy_guide = models.ForeignKey(User) I'd like to change this to class Company(models.Model): lucy_guide = models.ForeignKey(LucyGuide) However, when I implement this change and make and run migrations, I run into an IntegrityError: django.db.utils.IntegrityError: insert or update on table "lucy_web_company" violates foreign key constraint "lucy_web_company_lucy_guide_id_de643702_fk_lucy_web_" DETAIL: Key (lucy_guide_id)=(461) is not present in table "lucy_web_lucyguide". This question is similar to IntegrityError Insert or update on table "orders_order" violates foreign key constraint "; it seems like I have created LucyGuide objects before referencing them as foreign keys. What is the best way to fix this? Is there a series of commands I need to write in the shell to create these users? -
django 2: rendering both single post and suggested posts on a template
I am using Django 2 and I would like to display in a single article blog page both the body of that article and, at the bottom, 3 recommended articles. Unfortunately the display 3 articles part doesn't work. I receive no error it just doesn't display any part of the block from the loop more specifically: my view def detail (request, post_slug): post = get_object_or_404 (Post, slug=post_slug) suggested = Post.objects.all()[:3] return render (request, 'detail.html', {'post':post}, {'suggested':suggested}) and the html to display the suggested <section class="read-next"> {% for a in suggested.all %} <a href="/{{a.slug}}" class="prev-post " style="background-image:url({{a.image}})" > <div class="info"> <div class="tag">We recommend</div> <h3 class="post-title">{{a.title}}</h3> </div> </a> {% endfor %} </section> <!-- .read-next --> nothing gets rendered of this section or for wherever I add the loop. Thanks in advance for your help! -
how to highlight a choice in html when an user have chosen it (before submitted the choice)
Hi could you help me to solve the following problem? I am writing a web application in django. I would like to achieve the follow function in a page: When the user click the button of a choice, that choice would be made highlighted. As shown in this graph: page illustration In the views.py I wrote anscolor1 = "white" anscolor2 = "white" if request.method == "POST": completed_form = AnswerForm(request.POST) if completed_form.is_valid(): answer_value = completed_form.cleaned_data['answer'] if answer_value == 1: anscolor1 = "yellow" else: anscolor2 = "yellow" else: pass context = {'clr1': anscolor1, 'clr2': anscolor2} return render(request, 'polls/problems.html', context) In the html template I wrote <tr bgcolor = {{ clr1 }} > <td>Lottery 1</td> <tr bgcolor = {{ clr2 }} > <td>Lottery 2</td> But what the programming is doing is it highlights a lottery when the user had chosen it in the previous page (after the user submitted a choice). I understand that given the way I am coding now, it is supposed to be like this. But I am not sure how to read the value of answer_value before it is submitted. -
How to change the title of a webpage in a django template?
I tried to use "document.title" (in javascript) to set and change the title of a webpage which is situated between these two django tags: {% block title %}{% endblock title %} However, I am unable to achieve the desired effect. How should I change the content of this tag? Thanks in advance. -
Error with prewarming VersatileImageField
I've implemented django-versatileimagefield and have gotten it to a state where I can successfully resize images in templates with the use of the following tag, for example: As a result, I'm confident that my form.py, view.py, and template works. I have, however, recently tried to 'prewarm' the images so that when a user saves an image, a set of resized images are saved to my 'media' folder. This prevents the server from having to resize dynamically on every page load and can just grab the correctly sized image. My problem is that when the user goes to save an image within the image upload form, they get an error. Settings.py VERSATILEIMAGEFIELD_SETTINGS = { 'cache_length': 2592000, 'cache_name': 'versatileimagefield_cache', 'jpeg_resize_quality': 70, 'sized_directory_name': '__sized__', 'filtered_directory_name': '__filtered__', 'placeholder_directory_name': '__placeholder__', 'create_images_on_demand': False, 'image_key_post_processor': None, 'progressive_jpeg': False } VERSATILEIMAGEFIELD_RENDITION_KEY_SETS = { 'image_gallery': [ ('image_large', 'thumbnail__400x400'), ('image_small', 'thumbnail__900x900') ] } models.py from django.db import models from django.db.models.signals import post_save from versatileimagefield.fields import VersatileImageField from django.dispatch import receiver from versatileimagefield.image_warmer import VersatileImageFieldWarmer class ImageGallery(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) image = VersatileImageField('image_gallery', upload_to=upload_location) def __str__(self): return self.author.username @receiver(models.signals.post_save, sender=ImageGallery) def warm_gallery_images(sender, instance, **kwargs): gallery_img_warmer = VersatileImageFieldWarmer( instance_or_queryset=instance, rendition_key_set='image_gallery', image_attr='image_small' ) num_created, failed_to_create = gallery_img_warmer.warm() Traceback Environment: Request Method: … -
How does Django know that there is an include tag at the bottom of the page?
I am a beginner in Django, and I am really thoughtful about how things really work under the Django hood. I currently have this chunk of code to implement a pagination in a html file: {% extends "base.html" %} {% block title %}My Blog{% endblock %} {% block content %} <h1>My Blog</h1> {% for post in posts %} <h2><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2> <!-- How does this absurl work?--> <p class="date">Published {{ post.publish }} by {{ post.author }}</p> <!-- What does '.publish' print?--> {{ post.body|truncatewords:30|linebreaks }} {% endfor %} {% include "pagination.html" with page=posts %} <!-- The statement above is the little menu: "Page 1 of 2. Next" --> <!-- It also sends the 'page' variable as a GET parameter. --> {% endblock %} As I am using the for loop to load all the posts, and as the include "pagination.html" to load the pagination functionality is at the bottom of the code, how is it possible for Django to know that it should not display everything that it is supposed to in the for loop? Let's say I have 4 posts, and I would like to display just 3 posts in each page. -
Extending Django's User model with a OneToOneField: appropriate post_save signals when not every User is a CustomUser
I'm interested in extending the existing User model, using a post_save method to update the model as class LucyGuide(TimeStampedModel): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True) I'm following https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone, but there is a difference in my use case: every LucyGuide should have an associated User, but not every User is a LucyGuide. If I were to simply 'transcribe' the code from that example, I believe my receivers would look like this: @receiver(post_save, sender=User) def create_user_lucy_guide(sender, instance, created, **kwargs): if created: LucyGuide.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_lucy_guide(sender, instance, **kwargs): instance.lucyguide.save() As I understand it, however, the first method makes every User a LucyGuide, which is not what I want. Further, the second method would not always work since not every User has a lucyguide. Would I adapt this example as follows? @receiver(post_save, sender=User) def save_user_lucy_guide(sender, instance, **kwargs): if hasattr(instance, 'lucyguide'): instance.lucyguide.save()