Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django offset-naive date from DB
I just switched from django 1.3.7 to 1.4.22 (on my way to updating to a higher version of django). I am using USE_TZ=True and TIME_ZONE = 'Europe/Bucharest'. The problem that I am encountering is a DateTimeField from DB (postgres) that holds the value 2015-01-08 10:02:03.076+02 (with timezone) is read by my django as 2015-01-08 10:02:03.076000 (without timezone) even thou USE_TZ is True. Any ideea why this might happen? I am using python 2.7.12 AMD64. Thanks, Virgil -
How to distribute the filter result? (Django)
I want to retrieve 5 clothes for each parent_types ("top", "bottom", "shoes") user.clothes_set.filter(type="top")[:5] user.clothes_set.filter(type="bottom")[:5] user.clothes_set.filter(type="shoes")[:5] I want to do it more efficient way. (three filters are nasty!) top, bottom, shoes = user.clothes_set.filter(~~~) <- retrieve `5 items each` here is expected cloth models class Clothes(models.Model): id type = # top, bottom and shoes owner = ForeignField # some one who post Should I re-design the model? should I exclude the 'type' field to class? -
ImportError: No module named django.core
Good day. I changed my Python installation from 32 bit to 64 bit, after that my DJANGO stopped working. I searched the internet and finally added django to my site-packages and added django-admin.py to my path. Now, import django Works. But django-admin.py startproject wwwroot Doesn't work. It throws an exception: ImportError: No module named django.core Or could it be that there are complications with the former version of Python installed? How do I solve this -
How do i make a limit to "subscriptions" to my users on django models
this is the project How do i make a limit to "subscriptions" to my users on django models? for example: If "user" has more than 10 "Membri" can not or does not subscribe -
Django view arguments return the string of the view, not the intended value (for checking wrong password)
Here are my codes. The views.py. def index(request, wrong_password=False): print(wrong_password) return render(request, "app/index.html", { "user": request.user, "wrong_password": wrong_password } ) def login_function(request): user = authenticate( username=request.POST["username"], password=request.POST["password"] ) # For correct and wrong password. if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect(reverse("app:index")) else: return HttpResponseRedirect(reverse( "app:index", args=(True,) )) The urls.py. url(r"^$", views.index, name="index"), url(r"^(?P<wrong_password>\w+)/$", views.index, name="index"), I expect the print(wrong_password) (The 3rd line in def index(...)) to return True when the password inputted was wrong and return False for anything else. Without these codes, else: return HttpResponseRedirect(reverse( "app:index", args=(True,) )) my web application works fine. However, with it, the login() function does not work (it does not authenticate then login the user). Additionally, print(wrong_password) returns "login_manager" instead of True or False.. My intention is to make the user aware if the password inputted was wrong. How can I achieve this? -
How to use javascript to add form.action?
I am building django website, and have to use some select submit,my codes are: <form id='buttonform1' method='get'> <div class="control-group btn"> <div class="controls "> <select id="select01"> <option>2017</option> <option>2018</option> <option>2019</option> <option>2020</option> </select> <select id="select02"> <option>1</option> <option>2</option> <option>3</option> <option>5</option> <option>6</option> <option>7</option> <option>8</option> <option>9</option> <option>10</option> <option>11</option> <option>12</option> </select> <input type="button" value='submit' id='submit1'> </div> </div> </form> <script type="text/javascript"> $(document).ready(function(){ $("#submit1").click(function(){ var year=$('#select01').val(); var month=$('#select02').val(); var action1="?year="+year+"&month="+month alert(action1); document.getElementById('buttonform1').action=action1; document.getElementById('buttonform1').submit(); }); }) </script> the alert message is: ?year=2017&month=1 But submit result lost the action information: http://localhost/report/? If i change the action like this(delete '?'): var action1="year="+year+"&month="+month the result is: http://localhost/report/year=2017&month=1? What else can i do? thx -
Why does the html template in django display all possible messages of incorrect input before I even tried to input something?
I implemented django user authentication following this tutorial here is my html template: {% block title %}Регистрация{% endblock %} {% block additional_content %} <p class="scheise">Регистрация</p> {% endblock %} {% block content %} <div class = "sgnupform"> <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> </form> </div> {% endblock %} here is my class-based view: 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, 'signup.html', {'form': form}) yet somewhy messages indicative of incorrect input are displayed firsthand, before I even entered anything into a user form, and before I hit "enter": -
My Django model look inefficient. Can you suggest better model design? (I'm django beginner)
I'm modeling a simple Django model called "Clothes". Basically it retrieves what kinds of clothes the user have. I categorized clothes as more than 20 types (suchas hoodies, jean, pants) and as big three types: "top", "bottom", "shoes". In "ClothesView", I want to show first 5 clothes for each "top", "bottom", "shoes". And it will retrieve 5 more for individual category if user clicks more (So if user click 'more top', it will return 5 more clothes of 'top' type. For your better understanding, I wrote the 'Clothes' model conceptually. class Clothes(models.Model): id type = # hoodie, shirts, pants, jean, coat, and so on (more than 20) big_type = # top, bottom and shoes owner = ForeignField # some one who post Expected output (this is just my guess!) Retrieve 5 clothes for each parent_types ("top", "bottom", "shoes") user.clothes_set.filter(big_type="top")[:5] user.clothes_set.filter(big_type="bottom")[:5] user.clothes_set.filter(big_type="shoes")[:5] Retrieved 5 more clothes for "top" user.clothes_set.filter(big_type="top)[5:10] Retrieve all hoodies from my clothes <- this looks ok user.clothes_set.filter(type="hoodies") Can you suggest better of efficient model? I may add new Type class and put "through" ... (I'm not sure) -
wkhtmltopdf command works only under root user
I run wkhtmltopdf through Django application. On my PC (Ubuntu 16.04), it works correctly but on VPS (DigitalOcean Ubuntu 16.04) it does not. It raises: wkhtmltopdf exited with non-zero code -6. error: QXcbConnection: Could not connect to display I tried to check it through bash and found out that if I do this: wkhtmltopdf http://www.google.com google.pdf under the django user, it returns the same error: (homeitvenv) django@homeit-generator-faktur-beta:~/homeit$ wkhtmltopdf http://www.google.com google.pdf QXcbConnection: Could not connect to display Aborted (core dumped) But when I run it under root user, it works correctly: (homeitvenv) root@homeit-generator-faktur-beta:/usr# wkhtmltopdf http://www.google.com google.pdf Loading page (1/2) QFont::setPixelSize: Pixel size <= 0 (-1) ] 50% QFont::setPixelSize: Pixel size <= 0 (-1)====================] 100% QFont::setPixelSize: Pixel size <= 0 (-1) Printing pages (2/2) QFont::setPixelSize: Pixel size <= 0 (-1) QFont::setPixelSize: Pixel size <= 0 (-1) Done Do you have any idea why it doesn't work under the django? I've checked permissions under both users and it seems to be the same: django@homeit-generator-faktur-beta:~$ namei -m /usr/bin/wkhtmltopdf f: /usr/bin/wkhtmltopdf drwxr-xr-x / drwxr-xr-x usr drwxr-xr-x bin -rwxr-xr-x wkhtmltopdf django@homeit-generator-faktur-beta:~$ exit logout (homeitvenv) root@homeit-generator-faktur-beta:/usr/bin# namei -m /usr/bin/wkhtmltopdf f: /usr/bin/wkhtmltopdf drwxr-xr-x / drwxr-xr-x usr drwxr-xr-x bin -rwxr-xr-x wkhtmltopdf EDIT: This is my older question about running … -
NotUniqueError: Tried to save duplicate unique keys (E11000 duplicate key error collection: project.client index: UUID_1 dup key: { : null })
I am using django and mongoengine. This is the error I am getting time and again when I try to save a newly created instance using .save() method.I was able to create a model instance first time but after that any post request is raising this error. Here's my Document structure: class Client(DynamicDocument): name = fields.StringField(required=True,max_length=30) uuid = fields.UUIDField(default=uuid.uuid4()) contactEmail = fields.EmailField(required=True,max_length=30) contactPhone = fields.StringField(required=True,max_length=30) contactPerson = fields.StringField(required=True,max_length=30) class ClientSerializer(mongoserializers.DocumentSerializer): class Meta: model = Client fields = ('id','name','uuid','contactEmail','contactPhone','contactPerson') and here's where am making post request: def post(self, request, format=None): serializer = ClientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I am stuck here.Please tell me where I went wrong since I am a noob to django.Any help would be highly appreciated. -
Update a Django Filefield with Ajax
I'm trying to update an existing objects' FileField with Ajax. A wav blob is created in the browser, and I'm trying to pass it by appending it to a FormData instance: var data = new FormData(); data.append('sound', blob); $.ajax({ url: "{% url 'posts:update_audio' instance.pk %}", type: 'POST', data: data, cache: false, processData: false, contentType: false, success: function(data) { alert('success'); } }); return false; } I'm passing the pk through the url to the view, because (correct me if I'm wrong) but I think thats the way to specify the path to the correct objectt to be updated. Here is the view: def update_audio(request,pk): form = UpdateAudio(request.POST or None, request.POST or None) if request.method == 'POST': if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect('/') Which I just treated like any other view which submits a form. I'm a bit confused about how this is supposed to update the specific object, which leads me to my question: Should I be using a special view for this, like UpdateView? If so, how can I implement it? If not, anyone know where I'm going wrong? I'm currently just getting an internal server error 500 when I try and submit the form. -
Nested Django REST
It seems very simple to do nested serializer in Django REST. But I can not find anything wrong in my code.carts does not shown up I had followed http://www.django-rest-framework.org/api-guide/relations/#nested-relationships Only one thing different is I use JSONField. It should not be a problem. class MailAPIOrderItemSerializer(serializers.ModelSerializer): product = serializers.SerializerMethodField() category = serializers.SerializerMethodField() variant = serializers.SerializerMethodField() class Meta: model = OrderItem fields = ('category', 'product', 'variant') def get_variant(self, obj: OrderItem): return obj.product.get('level_two') def get_category(self, obj: OrderItem): return obj.product.get('service_name') def get_product(self, obj: OrderItem): return obj.product.get('product_name') class MailAPIOrderSerializer(serializers.ModelSerializer): ... carts = MailAPIOrderItemSerializer(many=True, read_only=True) class Meta: model = Order fields = ( ... 'carts' ) def get_staff_name(self, order: Order): return order.staff.full_name class OrderItem(AbstractSoftModelController): order = models.ForeignKey(Order, related_name='order_items', verbose_name=_('Order')) product = JSONField(verbose_name=_('Product')) My Temporal Solution: Right now. I am working around by replacing carts = serializers.SerializerMethodField() And in the method I use def get_carts(self, order: Order): qs = order.order_items.all() serializer = MailAPIOrderItemSerializer(qs, many=True) return serializer.data -
My system is not connecting to development server 127.0.0.1:8000 for a django project
I am using Windows 8.1.When i run a command to start the django server using python manage.py runserver it runs fine.But when i open 127.0.0.1:8000 in it the browser it says - This site can't be reached. 127.0.0.1 took too long to respond. I have already tried to change the port number by using python manage.py runserver 8080 but still it doesn't run. Please help me solving this issue. -
NOT NULL constraint failed - django
This is similar to a question i posted a while ago, but i have a different situation. I have a model with a form that is attached to the model. I am getting an not null constraint, but there is no field that is null so the constraint fail should not be coming up. I am not sure where this constraint fail is coming from... can someone help me just in case i dont see it. models.py dob_month = models.IntegerField(default=0) dob_day = models.IntegerField(default=0) dob_year = models.IntegerField(default=0) views.py section dob_month = form.cleaned_data.get("dob_month") dob_day = form.cleaned_data.get("dob_day") dob_year = form.cleaned_data.get("dob_year") new_profile = Profile.objects.create( user = currentUser, first_name = first_name, last_name = last_name, dob_month = dob_month, dob_day = dob_day, dob_year = dob_year, city = city, state = state, phone = phone, privacy = privacy, ) form post request dob_month : '6' dob_day : '14' dob_year : '2019' here is the exact error that is coming up... IntegrityError at /setup_profile/ NOT NULL constraint failed: tab_profile.dob_day Request Method: POST Request URL: http://127.0.0.1:8000/setup_profile/ Django Version: 1.8.6 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: tab_profile.dob_day -
Searching data in text file for output and convert to table dataframe.
in advanced sorry if I have any mistake during reading my questions: I'm working with Django and python for my website. The process I need to read input from the user for searching the directory file that I want to read which is I take 2 input, input1, and input2. I set the keyword in the variable if the keyword is matching I will print the next line. THIS IS MY TEXT FILE delay_index_time 775435 delay_index_time 456345 delay_index_time 4567867867868 delay_index_time 567867 Python Code In views.py def SearchBox(request): fullpath = "" input1= request.GET.get('input1') input2= request.GET.get('input2') input_combine = str(input1).upper() + "_" + str(input2) summary = '1A' search_string = 'delay_index_time' if input_Lot is None: return render(request, 'Output.html') else: path = "D:/file/" + str(input_combine) + "/" + summary with open(path) as input_data: for line in input_data: if search_string in line: context = { "output": (next(input_data)) } return render(request, 'Output.html', context) Template HTML <form id = "lol" class="navbar-form navbar-left" role="search" method="GET" action=""> <div class="input-group"> <input style="left:260px; width:250px; top:-80px;" id="box1" name="input1" type="text" class="form-control" placeholder="Lot"> <input style="left:270px; top:-80px; width:250px;" id="box2" name="input2" type="text" class="form-control" placeholder="Operation"> <div style="left:540px; top:-101px;" class="input-group-btn"> <a href="{% url 'Output' %}"><button id = "search_sub" value="Search" class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button></a> </div> </div> </form> {{ output|safe … -
The options auto_now, auto_now_add, and default are mutually exclusive. Only one of these options may be present
I get the bellow error in the console, when I run server in my PyCharm: ERRORS: frontend.Users.ctime: (fields.E160) The options auto_now, auto_now_add, and default are mutually exclusive. Only one of these options may be present. frontend.Users.uptime: (fields.E160) The options auto_now, auto_now_add, and default are mutually exclusive. Only one of these options may be present. My models Users code is below: class Users(models.Model): ctime = models.DateTimeField(auto_now_add=True, default=datetime.now()) uptime = models.DateTimeField(auto_now=True, default=datetime.now()) Why I get this error? -
Cannot access imported functions in django shell by pipeline command?
It is a python script tshi3.py : import csv def li2ho2(): print(csv) li2ho2() I copied this code and pasted it in python manage.py shell. It works. But I ran python manage.py shell < tshi3.py. Got NameError: name 'csv' is not defined. Why? Enviroment: Linux Mint 18.1 Python 3.4.1 (default, Sep 3 2014, 08:45:22) Django==1.11.4 There is a similar question. -
Django Data in Form Not Showing Up
I currently have an UpdateView and a button to edit data in fields, but for some reason the data is not being displayed when I click my edit button. It shows a bunch of empty fields unless I go to the address bar and press enter, basically requesting the same page. Then all the data shows up. Doesn't work when I click Edit, works when I press enter in address bar: /inventory/update/7/ views.py class ProductUpdate(UpdateView): model = Product fields = [ 'manufacturer', 'part_number', 'description', 'vendor', 'upc', 'stock_quantity', 'unit_cost', 'sale_price', ] urls.py # /inventory/update/<pk> url(r'update/(?P<pk>[0-9]+)/$', views.ProductUpdate.as_view(), name='product-update'), index.html <div class="col-sm-6"> <ul class="list-group"> {% for product in all_products %} <li class="list-group-item"> <a href="{% url 'inventory:product_detail' product.id %}"><span style="font-size: 1.6em;">{{ product.manufacturer }}: {{ product.part_number }}</span></a> <form action="{% url 'inventory:product-delete' product.id %}" method="post" style="display: inline"> {% csrf_token %} <button type="submit" class="btn btn-danger btn-sm float-right" style="margin-left: 10px; margin-top: 4px;">Delete</button> </form> <form action="{% url 'inventory:product-update' product.id %}" method="post" style="display: inline"> {% csrf_token %} <button type="submit" class="btn btn-warning btn-sm float-right" style="margin-top: 4px;">Edit</button> </form> </li> {% endfor %} </ul> </div> If I change the update form method to GET instead of POSTthen it works when I click the button, but my address bar shows up like this. /inventory/update/7/?csrfmiddlewaretoken=34WWjKDIDsNpZdmEmef9cr3tCoCO0V7jO3uks5qXFzSVKu1uAklqUA3ihaGBGaRK -
Django custom queryset inside ModelSerializer
I have a PostSerializer that has a comments field which use CommentSerializer. I want to change the queryset of this CommentSerializer so that it won't show all comments at once. Here's the code class PostSerializer(serializers.ModelSerializer): comments = SimplifiedCommentSerializer( many=True, required=False, ) class Meta: model = Post fields = ('comments') class SimplifiedCommentSerializer(serializers.ModelSerializer): content = serializers.TextField() # this function doesn't seem to work def get_queryset(self): return Comment.objects.all()[:10] class Meta: model = Comment fields = ('content') I've tried using get_queryset inside the SimplifiedCommentSerializer, but it doesn't work. -
Create a APP named admin in my project whether will get unknown conflict?
The django have a default module named admin. The red frame is created app by myself. Can I create a APP named admin in my project? I means if I do this, whether in the future I will get some unknown conflict? -
How to fast learn django restful API
I attempt learn Django restful API from http://www.django-rest-framework.org/ There are a lot of example in Tutorial.DO i need write a project with Tutorial? I don't know How to learn that -
all-auth SMTPAuthentication Error
I'm getting SMTPAuthenticationError at /rest-auth/password/reset/ error. I'm using all-auth-rest and set these on settings.py EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'randomemail@gmail.com' EMAIL_PORT = 25 # or 587 EMAIL_HOST_PASSWORD = 'mypassword' Also I enabled Displaying an Unlock Captcha and allowed less secure app access What is missing? Thanks -
Key Error with form - DJANGO
I have a project in django and I am creating a simple form that will allow a user to create a simple profile that asks for name and date of birth and location. I am getting a key error with the date of birth section and I dont know exactly why. I am trying to collect data and store it to then later added it to a database record. Here is the views file: cd = form.cleaned_data first_name = cd['first_name'] last_name = cd['last_name'] dob_month = cd['dob_month'] dob_day = ['dob_day'] dob_year = ['dob_year'] city = cd['city'] state = cd['state'] phone = cd['phone'] privacy = cd['privacy'] Here is the models file: user = models.ForeignKey(User, on_delete=models.CASCADE) # server first_name = models.CharField(max_length=25, default='first') last_name = models.CharField(max_length=25, default='last') dob_month = models.IntegerField(default=0) dob_day = models.IntegerField(default=0) dob_year = models.IntegerField(default=0) city = models.CharField(max_length=45) # user state = models.CharField(max_length=25, default='state') phone = models.BigIntegerField(default=0) # user privacy = models.SmallIntegerField(default=1) # user created = models.DateTimeField(auto_now_add=True) # server here is the forms file: class ProfileForm(forms.ModelForm): split_choices = (('1', 'public'), ('2', 'private')) privacy = forms.TypedChoiceField( choices=split_choices, widget=forms.RadioSelect, coerce=int ) dob = forms.DateField(widget=extras.SelectDateWidget) class Meta: model = Profile fields = ['first_name', 'last_name', 'dob', 'city', 'state', 'phone', 'privacy'] and finally, here is the error that … -
Django: Passing a static html file into view produce TemplateDoesNotExist error
I have a django app and a view for the home page where I want to use a static html file for the homepage. My file structure is like this: project/ stats (this is my app)/ urls.py views.py stats.html (other files here) In my views.py I have the following code: from django.shortcuts import render_to_response def index(request): return render_to_response('stats.html') When I run the urls, I just have the index page. I go to the stats page and I receive a TemplateDoesNotExist Error. Looking for an answer I tried to put stats/stats.html instead for the path, but I still get the same error. What is the correct way of doing this? -
Should I implement getStream on Back-End or Front-End?
I'm building my own social network service like Instagram. I'm using React Native for Mobile Front-End and Django RESTful Framework for BackEnd. In my case, should I implement getStream for my feeds and notification on Back-End or Front-End? (Django-python or React-Native JS)