Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not getting time from timezone.now in Django
My django model field for 'created_at' is models.DateTimeField(default=django.utils.timezone.now) And when I run 'django.utils.timezone.now()' in the interpreter from my app, I see datetime.datetime(2018, 9, 18, 15, 38, 7, 442631, tzinfo=<UTC>) but if I look in my database, I see (and return) only dates, not times, such like 2018-02-19 This is an inherited app, and despite a great deal of searching, I can't find anything that might be setting this to date only. -
Django image tag not displaying photo
I want to show an image by using a img src tag in a Django template file "index.html": templates/ index.html static/ img/ puzzle.png After adding the images to static I collected static and at the top of the page I included: {% load static %} And my image tag is: <img src="{% static 'img/puzzle.png' %}"> but the image is not showing up on my page. How can I fix this? -
Uploading Multiple Files using Django rest framework without using Forms
I'm trying to Post, from Postman, multiple files to my django app. I'm not using Forms, and there isn't a UI aspect to my app. Here is a my view class. class FileUploader(APIView): ''' Rest API for FileUploader ''' permission_classes = (AllowAny,) parser_classes = (MultiPartParser, ) @csrf_exempt def post(self, request): retval = Response(request.data, status=status.HTTP_201_CREATED) logger.info('New post with the following data: {}'.format(request.data)) With this it says, "TypeError: init() missing 3 required positional arguments: 'META', 'input_data', and 'upload_handlers'" If I use FormView, my Post has three keys, two represent files, the last is a string. During debugging my request has no field Data, and FILES is empty, and the POST doesn't have any information. Any pointers would be appreciated. I can upload more if that helps -
Django Nginx not working properly showing default page
I have an issue with ngnix on my site what I've just uploaded and configured on digitalocean. The issue is that when I visit the site, I see the ngnix default page (at mydomain.net) but if I type mydomain.net/myapp I see my django app working. Everything works fine except the homepage. I'm not sure what is this problem and I haven't find any solution for it online. My site is on the latest django release and debud False. The domain is added to allowed_hosts and also in the ngnix config. Does anyone have any idea what can be the problem? Thanks! -
Django; Is it possible to ignore this error? django.db.migrations.exceptions.InconsistentMigrationHistory:
I see the same error many people have seen. django.db.migrations.exceptions.InconsistentMigrationHistory: Migration message.0001_initial is applied before its dependency users.0001_initial on database 'default'. Seems like the cause is because I'm using CustomUser model (using django-allauth). I already delete all the migration folders and sqlite3 and tried some ways other people answered. But I cannot avoid this error. Seems like I was successful in avoiding this error (I have no idea how I did.) And because the migration files still remains on my gitHub, I saw them and all the files look the same as the ones I created before. I'm wondering if I can ignore this error and waring. If not, what is the way to avoid this error? what I did using --fake when doing migrations hiding django.admin when doing migrations applying zero all things failed. -
Test Driven Development with Django
I have a conceptual question about doing test driven development with Django, may also apply to other frameworks as well. TDD states that the firts step in the development cycle is to write failing tests. Suppose for a unit test, I want to verify that an item is actually created when a request arrives. To test this functioanlty, I want to issue a request with the test client, and check with the db that this object is actully created. To be able to do that, I need to import the related model in the test file, but as the first step is writing this test, I don't even have a model yet. So I won't be able to run the tests to see them fail. What is the suggested approach here? Maybe write a simpler test first, then modify the test after enough level of production code is implemented? -
Displaying ImageField list from Django Model
I looking to diplay a 'list' of images. I have a car info model and a database for associated pictures but an having a hard time figuring out how to get the images to display. Below is the error I currently get. Not Found: /cars/1/info_app/static/info_app/images/3323499244.jpg [18/Sep/2018 09:23:48] "GET /cars/1/info_app/static/info_app/images/3323499248.j pg HTTP/1.1" 404 2906 Also when I try to view the image in the admin page I get the error. Model_carspic with ID "22/change/info_app/static/info_app/images/2015-honda-civic-ex-front-left-angle-800x534-c.jpg" doesn't exist. Perhaps it was deleted? Model.py from django.db import models # Create your models here. # Create your models here. class model_cars(models.Model): model = models.CharField(max_length=128) make = models.CharField(max_length=128) year = models.CharField(max_length=128) price = models.CharField(max_length=128) mileage = models.CharField(max_length=128) color = models.CharField(max_length=128) engine = models.CharField(max_length=128) moreinfo = models.CharField(max_length=512) def __str__(self): return self.model def get_absolute_url(self): return reverse("info_app:cardetails",kwargs={'pk':self.pk}) class model_carspic(models.Model): pic = models.ImageField(upload_to='info_app/static/info_app/images/') car = models.ForeignKey(model_cars,models.CASCADE,related_name='carpic') views.py from django.shortcuts import render from django.http import HttpResponse from . import models from django.urls import reverse_lazy,reverse from django.views.generic import (View,TemplateView,ListView,DetailView) # Create your views here. class IndexView(TemplateView): # Just set this Class Object Attribute to the template page. # template_name = 'app_name/site.html' template_name = 'index.html' class view_about(TemplateView): # Just set this Class Object Attribute to the template page. # template_name = 'app_name/site.html' template_name … -
How to track email open by Python?
I was using Python to build auto email alert system. But sometimes, receiver didn't open the email which will delay the problem solving. I know we can add a 1*1 pixel image to email template to track Email Opens. But how to get the response back and display to a web page or email notice? Any thoughts will be appreciated. -
How to access from the list template to the detail template in Django 2?
I'm trying to access from the list template, to detail template Exmaple: article: urls article_patterns = [ path('', HomePageView.as_view(), name='home') path('articles/', ArticleListView.as_view(), name="articles"), path('articles/<int:pk>/', ArticleDetailView.as_view(), name="article"), ] main urls urlpatterns = [ path('', include(article_patterns)), path('admin/', admin.site.urls), ] In article_list.html <a href="{% url 'articles:article' article.id %}"> Detail {{articles.title}}</a> But I have this error: articles is not a registered namespace Any ideas or suggestions? -
Custom 403 error page in django rest framework
I am trying to override the default 403.html template of django rest framework, by declaring in ulrs.py handler403 = 'my_app.views.handler403'. And in the app's views.py: def handler403(request, exception, template_name='403.html'): response = render_to_response('403.html', {}) response.status_code = 403 return response The template's directory is included in TEMPLATE_DIRS in settings.py. However, making a request to an endpoint that has IsAdminUser permission, renders the default drf template. The same exact procedure for the 404 exception works perfectly fine. Any answer I saw in the web did not help me resolve the issue. -
How to get the name and url of an uploaded file when using models.FileField
I am using the following files: settings.py: MEDIA_URL = '/data/' MEDIA_ROOT = os.path.join(BASE_DIR, 'data') urls.py: urlpatterns = [ path("photo/upload", views.upload_pic, name="uploadpic ") ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py: class Pic(models.Model): name = models.CharField(max_length=255) photo = models.FileField(upload_to="data/media/%Y/%m/%d") def __str__(self): return self.url def path(self): return self.url forms.py: from django import forms class DocumentForm(forms.Form): docfile = forms.FileField( label='Select a file', help_text='any valid file' ) views.py: def upload_pic(request): documents = Pic.objects.all() import uuid name = uuid.uuid4().hex[:6].upper() if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): print(request.FILES) newdoc = Pic(name=name, photo=request.FILES['docfile']) newdoc.save() return render(request, 'clinic/list.html', {'documents': documents, 'form': form, 'msg': 'success'}) else: form = DocumentForm() # A empty, unbound form return render(request, 'clinic/list.html', {'documents': documents, 'form': form}) template: clinic/list.html {% extends 'clinic/newbase.html' %} {% load static %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p> {% endif %} <p><a href="{% url 'index' %}">Return to home</a></p> {% endblock %} However in the rendered html, the urls are blank: <body cz-shortcut-listen="true"> <!-- List of uploaded documents --> <ul> <li><a href=""></a></li> <li><a href=""></a></li> <li><a href=""></a></li> <li><a href=""></a></li> <li><a href=""></a></li> <li><a href=""></a></li> <li><a href=""></a></li> <li><a href=""></a></li> <li><a href=""></a></li> … -
Using CustomUser as author giving problem with database?
I am a little stuck, i am using CustomUser in settings (AUTH_USER_MODEL = 'users.CustomUser') and i want to use the username as author in comments. class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) text = models.TextField() when i run the migrations, it gives me this error return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for integer: "Alandivar" Alandivar being my superuser username in devmode, so how can i make it so when a customer put a comment in (requires login), the username is automatically used as author regards -
Django - How to filter through a ManyToManyField field?
Models: class Product(models.Model): ... options = models.ManyToManyField(Option, blank=True) class Option(models.Model): ... class ProductVariant(models.Model): ... product = models.ForeignKey(Product, on_delete=models.CASCADE) # parent product option = models.ForeignKey(Option, on_delete=models.DO_NOTHING, null=True) I need to find all the ProductVariants where the option doesn't belong to any options on the parent product Product. I tried doing the following filtering: ProductVariant.objects.exclude(option_id__in=[o.pk for o in F('product__options')]) But I got the following exception: 'F' object is not iterable -
Django JSON field in forms
here's my problem.I'm trying to create product variants which contain attribute values of the selected product. I'm trying to use JSONField to do that but I was wondering how I could dynamically display the fields in the form for creating new product variants. Here is my models.py file: class Product(models.Model) : name = models.CharField(max_length=120) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='products') allow_variants = models.BooleanField(default=True) product_attributes = models.ManyToManyField("attribute") def __str__(self) : return self.name class Meta : ordering = ("name",) class Attribute(models.Model) : name = models.CharField(max_length=120) def __str__(self) : return self.name def get_all_attr_variants(self) : variants = AttributeVariant.objects.filter(attribute__name=self.name) return variants class AttributeVariant(models.Model) : name = models.CharField(max_length=120) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) def __str__(self) : return self.name class Meta : ordering = ('name',) class ProductVariant(models.Model) : product = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(max_length=120) price = models.DecimalField(max_digits=10, decimal_places=2) attributes = JSONField() def __str__(self) : return self.product.name + ": " + self.name class Meta : ordering = ("product.name", "name") Please help me if you have any idea of how I could solve this problem! Thanks -
Postgresql; Why hasn't postgresql/data folder been removed?
I try to uninstall Postgresql completely. But even though most application is already uninstalled, PostgreSQL/data folder has not been removed. Is it oaky to delete this folder manually? Or is there a way to delete this folder correctly. The reason I asked this question is that I cannot use postgresql for my Django project. I posted the question here Django; django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host, user, database Basically when I do python manage.py makemigrations, django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host, user, database SSL off no pg_hba.conf entry for host, user, database SSL on this error happens. I actually have used postgresql for other Django project before and this is the first time I encountered this error. I don't know why this error happens but I think this error happens after I installed Postgresql application on my windows.(I already uninstalled all application a few month ago and folder but still there's an error.) And I wondered if I can delete this folder manually. I installed Postgrsql again so I try to fix this error and tried many things other people answered. (like edited pg_hba.conf but never fixed this error. https://dba.stackexchange.com/questions/83984/connect-to-postgresql-server-fatal-no-pg-hba-conf-entry-for-host) I've been following this tutorial always https://www.youtube.com/watch?v=t6RbanOhna4 I … -
How to implement get_template_names() function in CBV?
I have two list views for a same model I want to specify template for one view using get_template_names() function, But cannot resolve how to perform this... This is my two views look like: class bloglistview(LoginRequiredMixin,ListView): model = Blog def get_queryset(self): return Blog.objects.filter(User=self.request.user).order_by('id') def get_context_data(self, **kwargs): context = super(bloglistview, self).get_context_data(**kwargs) context['categories_list'] = categories.objects.all() return context class allbloglistview(LoginRequiredMixin,ListView): model = Blog def get_queryset(self): return Blog.objects.all().order_by('id') def get_context_data(self, **kwargs): context = super(allbloglistview, self).get_context_data(**kwargs) context['categories_list'] = categories.objects.all() return context Can Anybody help me out on this? -
bootstrap-datepicker and django template, an easy way
I would like to use date picker in my template. Is there a way to omit stuff in forms.py and simply do something like: <tr class="new"> <form method="post">{% csrf_token %} <td> <input size="10" type="text" class="form-control" id="date" name="{{ form.date }}"> <script type="text/javascript"> $("#date").datepicker({format: "dd/mm/yyyy", autoclose: true}); </script> </td> ... that is, to use the {{ form.date }} as a name in input for example? Unfortunately this solution doesn't work for me -
Django Foreign key in another schema
I have a MySQL database with 2 shemas (A & B). My django app can read & write into A. It can just read from B. My app managed all the tables in A. B already contains some data in a table (b). I want to add a Foreign Key between A and B. Something like this : class SchemaBTableB(models.Model): class Meta: managed = False db_schema = 'B' db_table = 'b' [...] class SchemaATableA(models.Model): class Meta: db_schema = 'A' db_table = 'a' id = models.OneToOneField( SchemaBTableB, on_delete=models.DO_NOTHING, primary_key=True ) [...] Unfortunately, db_schema does not exist. Does someone know a solution ? -
Django admin slow using TabularInline with many to many field
I'm trying to use Django admin to visualize all samples in one request. It works, but it is really slow. I tried to use prefetch, formset, raw_id_fields, and readonly_fields with no luck. It is still very slow when I load more than 10 samples. I'm having a N+1 problem here. I checked on Django debug toolbar and it makes a query for each sample in that request. Here are my models: # This is where the sample has all information class Inventory(models.Model): sample_id = models.CharField(max_length=50, primary_key=True) def __str__(self): return '{0}'.format(self.sample_id) # Intermediate model class SampleRequestInventory(models.Model): sample = models.ForeignKey("Inventory", on_delete=models.CASCADE) request = models.ForeignKey("SampleRequest", on_delete=models.CASCADE) # This is the request model that I'm looking class SampleRequest(models.Model): samples = models.ManyToManyField("Inventory", through="SampleRequestInventory") Here are my django admin configuration: class SamplesInline(admin.TabularInline): model = SampleRequestInventory # raw_id_fields = ('sample',) readonly_fields = ('sample',) extra = 0 # this formset did not work either # class MyInlineFormset(BaseInlineFormSet): # def __init__(self, data=None, files=None, instance=None, # save_as_new=False, prefix=None, queryset=None, **kwargs): # super(MyInlineFormset, self).__init__(data, files, instance, # save_as_new, prefix, queryset, **kwargs) # self.queryset = SampleRequest.objects.all(). \ # prefetch_related('samples') class SampleRequestAdmin(admin.ModelAdmin): # This queryset for prefetching only makes an extra query... def get_queryset(self, request): qs = super(SampleRequestAdmin, self).get_queryset(request) return qs.prefetch_related('samples') # extra … -
Django filter by field named 'id' in JSONField
I have Django application and PostgreSQL database. My problem is that I cannot filter by field named 'id' in JSONField. My model looks like that: class SnapshotAuditing(models.Model): data = JSONField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) And populate it with data like that: snapshot = SnapshotAuditing( data={ 'id': student.id, 'some_value': some_value, } ) snapshot.save() Than I want to perform the following select request: price_change = SnapshotAuditing.objects.filter( data__id=student.id ).order_by('created').first() But I get this error: FieldError: Unsupported lookup 'id' for JSONField or join on the field not permitted. Can you help with it, please? -
Django BinaryField sqlite vs postgres
The same field in my models return different data per field. The postgresql returns a memoryview,while sqlite returns bytes(). How can I change the return type of the postgres binaryfield to bytes()? -
Allow automatic redirection of the browser using Meraki Captive Portal API
I am working with the Meraki Captive Portal API. The flow is like this. Login form containing username and password. I collect the username and password from the form and use post the details to login_url provided. Once authentication is successful, a GET is done automatically to a new page. Code for login is as below: def index(request): # if this is a POST request we need to process the form data if request.method == 'POST': username = request.POST['username'] code = request.POST['code'] login_url = request.session['login_url'] continue_url = 'http://' + request.get_host() + reverse('splash:home') login_params = {"username": username, "password": code, "continue_url": continue_url} r = requests.post(login_url, params=login_params) # if a GET (or any other method) we'll create a blank form else: login_url = request.GET['login_url'] continue_url = request.GET['continue_url'] ap_name = request.GET['ap_name'] ap_mac = request.GET['ap_mac'] ap_tags = request.GET['ap_tags'] client_ip = request.GET['client_ip'] client_mac = request.GET['client_mac'] request.session['login_url'] = login_url request.session['continue_url'] = continue_url request.session['ap_name'] = ap_name request.session['ap_mac'] = ap_mac request.session['ap_tags'] = ap_tags request.session['client_ip'] = client_ip request.session['client_mac'] = client_mac return render(request, 'splash/index.html') The problem is here: r = requests.post(login_url, params=login_params) Everything goes fine. However, am not being redirect when the Meraki API does a GET request. Am still at the login page. What can I do to the view … -
Django Ajax Comment System
I want to create a comment system with using Ajax. My main purpose is getting new comments in my page without page refreshing. I add some js code to my HTML file but it didn't work. Where are my mistakes and what should I do? views.py ... def post_detail(request, pk, ): post = get_object_or_404(Post, pk=pk) form = CommentForm(request.POST or None) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) context = { 'post': post, 'form': form, } return render(request, 'blog/post_detail.html', context) comments.html {% load crispy_forms_tags %} {% load static %} <hr> <form method="POST" style="width: 50%; margin-left: 20px" id="comment_form"> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn btn-info" value="Yorum Ekle" style="margin-left: 20px"> </form> <script type="text/javascript" src="{% static 'js/jquery-1.11.1.min.js' %}"></script> <script type="text/javascript"> $(document).on('submit', '#comment_form', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'post_detail', data: { name: $('#name').val(), content: $('#content').val(), created_date: $('#created_date').val(), post: $('#post').val(), csrfToken: $('input[name=csrfmiddlewaretoken]').val() }, success: function () { alert("YEAH"); } } ) }) </script> post_detail.html ... {% include 'blog/comment.html' %} <hr> {% for comment in post.comments.all %} <h4>{{ comment.name }} | <small>{{ comment.created_date|timesince }} önce</small></h4> <p>{{ comment.content|linebreaks }}</p> {% endfor %} urls.py ... url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'), When I click comment button there is no action. But … -
django ORM with asyncio
I'm looking for something that can allow the usage of the Django ORM with asyncio (with PostgreSQL). As of now I found only aiopg in the asyncio ecosystem, which allows to run raw SQL or to use SQLAlchemy only. I then found something in the django channels docs. is this: https://github.com/django/channels/blob/master/channels/db.py the missing piece that I was looking for? Thanks Thanks -
How to serialize result of objects.filter django based on foreign key object
I have two models one with a foreign key to the other: class Booking(models.Model): type_course_requested = models.ManyToManyField(TypePost, blank=True) ..... #Presentation Message message = models.CharField(max_length=1000) class BookingDemand(models.Model): booking = models.ForeignKey(Booking, on_delete=models.CASCADE, null=True, blank=True) I want to get bookingdemands based on certain condition, and then serializing to have something like this: { 'booking1': { 'key1':... 'bookingDemands': {....} }, 'booking2': {...} } Filtering is done like this: bookings=BookingDemand.objects.filter(booking__post__person=self.request.user) which returns a queryset, but I can't find how to serialize them to have each booking separatly as mentionned above.