Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse lookup in django
I have two models as follows class IntakeDetails(models.Model): intake = models.ForeignKey(intake, on_delete=models.CASCADE) lecturer = models.ForeignKey(Lecturer, on_delete=models.CASCADE) module= models.ForeignKey(Module, on_delete=models.CASCADE) class AssignAssignment(models.Model): title=models.CharField(max_length=30) duedate=models.DateField() intakedetails=models.OneToOneField(IntakeDetails, on_delete=models.CASCADE,related_name='details' I have a queryset queryset = IntakeDetails.objects.filter(lecturer=self.request.user.id) it filters all the intakedetails that belong to that lecturer in that table. but i want it to filter that intakedetails that doesnt exist in assign assignment model. anyone can help ? -
order_by does not sort Swedish UTF-8 characters ÅÄÖ correctly on production server
I'm experiencing some issues with my production droplet @ DigitalOcean when sorting querysets. The Swedish characters ÅÄÖ are treated as A and O, which is not expected or desired. This works locally. I've dabbled with the locales on the server, and they seem to be alright. Django version: 1.11 Python version: 3.5.2 If anyone have experienced & solved similar issues, it would be great to hear how you solved it! Model definition class County(TimeStampedModel): name = models.CharField(max_length=200, unique=True) def __str__(self): return self.name How the queryset is sorted. County.objects.all().order_by('name') -
jquery upload files and django forms
Hello everyone i trying add multi upload images to my product form, with jQuery File Upload. At first i need to create product and then add images to this product. If am doing in my views like this: VIEWS: def addprod(request): form = ProductForm priceforms = ProductPricesFormSet if request.method == 'POST': form = ProductForm(request.POST) priceforms = ProductPricesFormSet(request.POST) imageform = ProductImageForm(request.POST, request.FILES) if form.is_valid() and priceforms.is_valid() and imageform.is_valid(): # PRODUCT SAVE product = form.save(commit=False) product.shop_owner = request.user.shop product.save() # PRICES SAVE prices = priceforms.save(commit=False) for price in prices: price.product = product price.save() # IMAGE SAVE image = imageform.save(commit=False) image.product = product image.save() files = [serialize(image)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(request)) response['Content-Disposition'] = 'inline; filename=files.json' return response else: data = json.dumps(imageform.errors) return HttpResponse(content=data, status=400, content_type='application/json') return render(request, 'add_product.html', {'form': form, 'priceforms': priceforms}) i am getting error "The 'file' attribute has no file associated with it." serializers def order_name(name): name = re.sub(r'^.*/', '', name) if len(name) <= 20: return name return name[:10] + "..." + name[-7:] def serialize(instance, file_attr='file'): obj = getattr(instance, file_attr) return { 'url': obj.url, 'name': order_name(obj.name), 'type': mimetypes.guess_type(obj.path)[0] or 'image/png', 'thumbnailUrl': obj.url, 'size': obj.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', } -
Django: kwargs of ModelForm
I have to models called Event and Registration. Here you can see my admin.py: class RegistrationInline(admin.StackedInline): model = Registration form = RegistrationForm # inherits from ModelForm def has_add_permission(self, request): return False @admin.register(Event) class EventAdmin(admin.ModelAdmin): form = EventForm inlines = [RegistrationInline] In my RegistrationForm I have this here because I need the pk of the Event: def __init__(self, *args, **kwargs): self.event = kwargs.get('instance').event # In my Registration model "Event" is a ForeignKey super().__init__(*args, **kwargs) When I go in my Admin and go to a Event, the output of kwargs is: {'auto_id': 'id_%s', 'prefix': 'registration_set-0', 'error_class': <class 'django.forms.utils.ErrorList'>, 'use_required_attribute': False, 'instance': <Registration: 1>} {'auto_id': 'id_%s', 'prefix': 'registration_set-1', 'error_class': <class 'django.forms.utils.ErrorList'>, 'use_required_attribute': False, 'instance': <Registration: 2>} {'auto_id': 'id_%s', 'prefix': 'registration_set-2', 'error_class': <class 'django.forms.utils.ErrorList'>, 'use_required_attribute': False, 'instance': <Registration: 3>} {'auto_id': 'id_%s', 'prefix': 'registration_set-3', 'error_class': <class 'django.forms.utils.ErrorList'>, 'use_required_attribute': False, 'instance': <Registration: 4>} {'auto_id': 'id_%s', 'prefix': 'registration_set-__prefix__', 'empty_permitted': True, 'use_required_attribute': False} {'auto_id': 'id_%s', 'prefix': 'registration_set-__prefix__', 'empty_permitted': True, 'use_required_attribute': False} {'auto_id': 'id_%s', 'prefix': 'registration_set-__prefix__', 'empty_permitted': True, 'use_required_attribute': False} My problem are the last three lines. Becuase there is no instance my approach does not work. How can I remove those three lines or what do those three lines mean? -
socket.gaierror: [Errno 11004] getaddrinfo failed,django
I am trying create a Betfair interactive login following this [tutorial ][1] and i keep on getting and error my app_key is correct and my username and password also correct but i think i am not getting hoe to set it to work correctly please any help will be grateful here is my code import requests import json login_hearders = { 'Accept' : 'application/json', 'X-Application':APP_KEY_HERE, 'Content-Type':'application/x-www-form-urlencoded '} url = 'https://identitysso.betfair.au/api/login' payload = {'username':'USERNAME_HERE','password':'PASSWORD_HERE'} r = requests.post(url, data=payload,headers=login_hearders) print(json.loads(r.text)) -
How to display book image from Google Books API in dango
I am trying to get Image from google books API I have a link like this :http://books.google.com/books/content?id=l5BohvUh-EUC&printsec=frontcover&img=1&zoom=1&source=gbs_api which gives a image. But if i save it to a django ImageField, and when i open, it becomes http://127.0.0.1:8000/media/http%3A/books.google.com/books/content%3Fid%3Dl5BohvUh-EUC%26printsec%3Dfrontcover%26img%3D1%26zoom%3D1%26source%3Dgbs_api which is obviously 404 Page not found. I could do this by saving the image to media folder, but this is not what i want to do. I want to access it as image just like it when it is inside the media.folder. How to do this ? -
How do I sort Django models by sum of calculated property?
I have two models, Project and Session. One project has many sessions, one user has many projects: class Project(models.Model): class Meta: ordering = [models.functions.Lower("name")] name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) class Session(models.Model): start = models.DateTimeField() end = models.DateTimeField() timezone = TimeZoneField() breaks = models.IntegerField(default=0, validators=[MinValueValidator(0)]) project = models.ForeignKey(Project, on_delete=models.CASCADE) def duration(self): # returns minutes in (end - start) I want a way to get all projects for a given user, sorted by the sum of duration in all its sessions. As session.duration() is not a database field, but rather is calculated from database fields, I cannot get this information in a single database query. My current solution is: sessions = Session.objects.filter(project__user=self) groups = [[a, sum([s.duration() for s in b])] for a, b in groupby( sessions, key=lambda s: s.project )] groups = sorted(groups, key=lambda g: g[1], reverse=True) return [g[0] for g in groups] This gets all relevant sessions in a single query, but then I group them by project and this takes too long - about a second when there are about a 100 projects. Is there a way to accomplish this that takes less time? And ideally doesn't require a database call for every project? I am using Django … -
How can I order post entries in a Django template
I made my post model where I store all the post info, like the title, the body, the tags an so on. And I linked it to my index template with a for loop: <!-- Blog Post --> {% for blog in object_list %} <div class="card mb-4"> <div class="card-body"> <h4 id="post_title" class="card-title">{{blog.title}}</h2> <div id="post_body" class="card-text">{{blog.formatted_markdown|safe}}</div> <a href="details/{{blog.id}}" class="btn btn-primary">Read More</a> </div> <div class="card-footer text-muted"> <p id="foot_page">{{blog.date}}</p> <a id="foot_page" href="#">{{blog.author}}</a> </div> </div> {% endfor %} And when I run my server the post appear on the blog ordered by pub_date ascending, so the new ones appear delow the old ones. What can I do to make the newest post appear on top? Here's my Post model class if it's useful: class Post(models.Model): title = models.CharField(max_length=255) body = MarkdownxField() tags = models.ManyToManyField(Tag) author = models.CharField(max_length=255, default='Raúl Chirinos') date = models.DateTimeField(auto_now_add=True, blank=True) @property def formatted_markdown(self): return markdownify(self.body) def __str__(self): return self.title -
Django instert utf8 text in textarea editor
I have a utf8 text that I'm trying to insert into a textarea. The code is pretty simple: let initial_description = "{{ initial_decription }}"; $("#descripcion").html(initial_description); But I get this error: SyntaxError: unterminated string literal -
Django: projectoverview() missing 1 required positional argument: 'project_id'
When I try to run the page /work/, I get the following error message: TypeError at /work/ work() missing 1 required positional argument: 'project_id' Request Method: GET Request URL: http://72.132.209.86:8000/work/ (Not my real ip) Django Version: 2.0.5 Exception Type: TypeError Exception Value: work() missing 1 required positional argument: 'project_id' Exception Location: /usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py in _get_response, line 126 Python Executable: /usr/bin/python3 Python Version: 3.5.2 My code is: views.py def work(request): projectslist = Project.objects.order_by('project_name')[:5] context = { 'projectslist': projectslist, } return render(request, 'mywebsite/work.html', context) def project(request): return render(request, 'mywebsite/project.html') urls.py path('work/', views.work, name='work'), path('<int:project_id>/', views.project, name='project'), models.py class Project(models.Model): project_name = models.CharField(max_length=200) project_title = models.CharField(max_length=100) project_information = models.CharField(max_length=400) project_link = models.CharField(max_length=30) project_icon = models.CharField(max_length=40) project_category = models.CharField(max_length=50) def __str__(self): return self.project_name work.html {% extends 'mywebsite/base.html' %} {% block content %} <ul> {% for project in projectslist %} <li><a href="{% url 'project' project.id %}">Testtest</a></li> {% endfor %} </ul> {% endblock %} I do know that there is something wrong with the link, namely that it doesn't recognize the project.id, but I do not know what the origin is of this problem. The database that I am using is sqlite3 and I have two projects registered (on pk=3 and pk=4) -
how to replace ('delete/<int:id>', views.destroy) <int:id> with varchar in url patterns as I am trying to delete existing record by name
from django.contrib import admin from django.urls import path from EMSapp import views urlpatterns = [ path('admin/', admin.site.urls), // to access admin page path('emp', views.emp), // to access index page path('show',views.show), // to access output of index page path('edit/<int:id>', views.edit), path('update/<int:id>', views.update), path('delete/<int:id>', views.destroy), ] I am trying to even perform edit,update and delete operations by 'name' along with 'Id'. How to proceed ? -
Django operational error
Not able to run the server because of operational error(django.db.utils.OperationalError: (1045, "Access denied for user 'mounikasmitha'@'localhost' (using password: NO)")). As I have synced the database in settings.py file. Not able to trace the perfect solution. All suggestions are welcome, the below picture is the settings.py file. -
How to use django-trix in a Django Project?
I have added trix in my model.py from trix.fields import TrixField ..... class Article(models.Model): title = models.CharField(max_length=100) content = TrixField('content') time_added = models.DateTimeField(default=timezone.now) def __str__(self): return 'Article Name: {}, Added: {}'.format(self.title, self.time_added) ..... It shows results like this photo bellow in my Django-admin which I loved: but it doesn't shows my desired output in my Template How can I fix it -
Django - show the query in the search box on the results page
I'm trying to show User's search query in the Search Box on the results page. A very basic problem, but for some reason, it doesn't work for me. My views.py looks like: def search(request): result_list = [] if request.method == 'POST': query = request.POST['query'].strip() if query: print(query) print(type(query)) # Run our Webhose search function to get the results list! result_list = run_query(query) context_dict = {'result_list': result_list, 'query': query} context_dict = {'result_list': result_list} return render(request, 'rango/search.html', context_dict) my search.html template is below: {% block body_block %} <div> <h1>Search with Rango</h1> <br/> <form class="form-inline" id="user_form" method="post" action="{% url 'search' %}"> {% csrf_token %} <div class="form-group"> <input class="form-control" type="text" size="50" name="query" value="{{query}}" id="query" /> </div> <button class="btn btn-primary" type="submit" name="submit" value="Search">Search</button> </form> <div> {% if result_list %} <h3>Results</h3> <!-- Display search results in an ordered list --> <div class="list-group"> {% for result in result_list %} <div class="list-group-item"> <h4 class="list-group-item-heading"> <a href="{{ result.link }}">{{ result.title }}</a> </h4> <p class="list-group-item-text">{{ result.summary }}</p> </div> {% endfor %} </div> {% endif %} </div> </div> {% endblock %} Any advice? -
Django Rest Framework - Serializer validation doesn't work
I have simple serializer in my serializers.py and I want to validate one of the fields using validate(self, data) but it doesn't work. Here is my code: class DataUpdateSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField(write_only=True) def validate(self, data): if data['username'] != 'test': raise serializers.ValidationError('Wrong username') return data I don't know if it will help but here are my views.py class DataUpdateAPI(views.APIView): serializer_class = DataUpdateSerializer def post(self, request): username = request.POST.get('username') password = request.POST.get('librus_password') return Response("Just test response") I don't know what's wrong with this code. Thanks in advance for the help! -
NoReverseMatch at ListView with Form
Ii got an error after add form to my ListView class. here my models.py class Holiday(models.Model): name = models.CharField(max_length=100) date_from = models.DateField() date_to = models.DateField(null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("app:holiday_list" here my views.py class HolidayListView(ListView): context_object_name = 'holidays' model = models.Holiday class HolidayCreateView(CreateView): fields = ('name', 'date_from', 'date_to') model = models.Holiday and here my holiday_list.html .... <form method="post" action="{% url 'holiday-create' %}"> {% csrf_token %} <input type="text" name="name" maxlength="100" required="" id="id_name"> <input type="text" name="date_from" required="" id="id_date_from"> <input type="text" name="date_to" required="" id="id_date_to"> <input type="submit" class="btn btn-primary" value="Submit"> </form> .... some code to list all data and my urls.py url(r'^/$',views.HolidayListView.as_view(), name='holiday_list'), url(r'^create/$',views.HolidayCreateView.as_view(),name='holiday-create'), i got an error : NoReverseMatch at /app/holiday/ Reverse for 'holiday-create' not found. 'holiday-create' is not a valid view function or pattern name. did I miss something. -
I got a redirect_uri_mismatch error on django-allauth and github
I got the error message from Django's console. Why I got this error? I read and tried by this tutorial. "GET /accounts/github/login/callback?error=redirect_uri_mismatch&error_description=The+redirect_uri+MUST+match+the+registered+callback+URL+for+this+application.&error_uri=https%3A%2F%2Fdeveloper.github.com%2Fapps%2Fmanaging-oauth-apps%2Ftroubleshooting-authorization-request-errors%2F%23redirect-uri-mismatch&state=cpybsYqLpapp HTTP/1.1" 301 0 Github app screenshot -
How can make a dynamic data in Django template?
example views: dinamic=0 while dinamic<10: dinamic=dinamic+1 how can I render on my template 1 then 2 then 3 ... makes the page reload -
Rendering view from form in Django
I'm having issue getting the content from a form and displaying it on another page. When I click submit, it directs me to the correct page but it does not load as there are errors in my function. I am also unsure how to display the content on the page. My form: <div class = "container"> <form action="{% url 'cleaner:result' %}" method ="post" > {% csrf_token %} <div> <label for="cv">Enter details: </label> <textarea name="cv" id='cv' rows="10" cols="30" maxlength="20000"></textarea> </div> <div> <button>Submit</button> </div> </form> </div> urls.py url(r'clean/result/$', views.ResultView.as_view(), name='result'), My issue lies here, in views.py class ResultView(View): template_name = 'cleaner/result.html' #Get details from form details = request.form.get("cv") def result(request): if details != '': return render(request, template_name) This is not the correct way to get the content from the form. How can I get this? details = request.form.get("cv") NameError: name 'request' is not defined After that, how do I display the content of the form? I am using django 1.9 and python 3.6.4. -
When I switch to another User's profile page, it automatically logs in to their account
I am building a sort of facebook replica, but whenever I go to someone else's profile page, It automatically logs in to their account. I looked at the code, and it seems like the 'user' object keeps changing. I figured it is related to sessions and keeping the user logged in. i.e there could be something missing from the login view logic. here's what I have: accounts.views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.models import User from django.contrib import auth from groups.models import Group from posts.models import Post from friends.models import Friend # Create your views here. def home(request): return render(request, 'accounts/home.html') def signup(request): if request.method == 'POST': if request.POST['password1'] == request.POST['password2']: try: User.objects.get(username=request.POST['username']) return render(request, 'accounts/signup.html', {'error': "An account with this username already exists"}) except User.DoesNotExist: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) auth.login(request, user) return redirect('groups:index') else: return render(request, 'accounts/signup.html', {'error':'The passwords do not match'}) else: return render(request, 'accounts/signup.html') def login(request): if request.method == 'POST': user = auth.authenticate(username=request.POST['username'], password=request.POST['password1']) if user is not None: auth.login(request, user) return redirect('groups:index') else: return render(request, 'accounts/login.html', {'error':"An account with this information does not exist"}) else: return render(request, 'accounts/login.html') def logout(request): if request.method == 'POST': auth.logout(request) return redirect('accounts:login') def profile(request, user_id): user = get_object_or_404(User, pk=user_id) … -
django-channels real time notifications after commenting item
models.py: class Question(models.Model): user = models.ForeignKey(User) name = models.CharField() content = models.TextField() class Comment(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE,related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() I have two logged in users, USER_A and USER_B. USER_B added new question. USER_A just commented this question. How should I handle this in django-channels to send notifications to question owner if somebody comment their question + notification to the other peoples whos commented this question? I'm really confused how to design this. -
How it works (cleaned_data Django)
I'm studying python and django. I'm still a begginer, but i like this things. I don't understand how cleaned_data works and what it do. Thanks -
How to configure stream-django with DRF
I am using stream-django to create newsfeed in my DRF project but when I am trying to add an activity I am getting this error, StreamApiException: GetStreamAPI404 I have properly mentioned the STREAM_API_KEY and STREAM_API_SECRET Could you please help me, I am using stream-django for the first time? -
Django: Pass parameter to Form in Admin
I have two models called Event and Registration. Each Registration has as ForeignKey an Event object. Now, in my web application I provide a RegistrationForm so that people can register for an event. Example: A user can register at /event/<pk>/register/. From the URL I get the event the user would like to register for and pass the public key of the event to the RegistrationForm. class RegistrationForm(forms.ModelForm): class Meta: model = Registration exclude = ['event'] def __init__(self, *args, **kwargs): self.bus = kwargs.pop('pk') super().__init__(*args, **kwargs) In the form I, of course, do not display the event field (so that's why it's excluded). Because when the user is at e.g. /event/5/register/ is clear that he would like to register for event 5. In the view I create the Form using form = RegistrationForm(pk=pk). In case you know a better solution how to solve this, please come up with it. :) Now the problem: In my RegistrationForm I have also some validation logic and when I create a new Registration object in the Admin, I'd also like to have those validations. But it does not seem right to create a new Form only for the admin and to copy and paste the validation … -
a function to check if a string is exactly match with regix
I'm looking for a true-false returning function that returns true when the string is exactly matched with the regex and false when it is not in python I tried re.match() and re.search() but these functions return true when just a part of the string is matched.please help!