Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Print related object of related object python
I am creating a guide app where each guide is made of 3 classes as bellow. How do I for example print subtask 3 of step 2 in guide 1 class Guide(models.Model): user = models.ForeignKey(User, default=1) guide_category = models.CharField(max_length=250) guide_title = models.CharField(max_length=500) guide_how = models.CharField(max_length=100) guide_why = models.CharField(max_length=100) guide_logo = models.FileField() is_complete = models.BooleanField(default=False) def __str__(self): return self.guide_title + ' - ' + self.guide_category + ' - ' + self.guide_how + ' - ' + self.guide_why class Step(models.Model): guide = models.ForeignKey(Guide, on_delete=models.CASCADE) step_title = models.CharField(max_length=250) is_complete = models.BooleanField(default=False) def __str__(self): return self.step_title class Subtask(models.Model): step = models.ForeignKey(Step, on_delete=models.CASCADE) subtask_title = models.CharField(max_length=250) subtask_description = models.CharField(max_length=250) subtask_image = models.FileField() is_complete = models.BooleanField(default=False) def __str__(self): return self.subtask_title Thanks! :) -
Django list ordering by date
I want to display in the same page all the results of this 2 querries and ordering them by date. The goal is to mix both results to just display a unique list ordering by date. articles = Articles.objects.all() statut = Statut.objects.all() I have this idea but I don't know : articles = list(Articles.objects.all()) statut = list(Statut.objects.all()) all = articles + statut So I have a unique list and it's working. It displays every results. Now I wonder how to order by date for the template rendering ? May be there is a simplier way to do it ? Thank you. -
Django email settings
I'm trying to send some emails for my application. The thing is, doing some tests I see that for some reason my "From email" that I import from the settings change to some string, and for that the mail never gets send. from django.test import TestCase from django.conf import settings from django.core import mail class TestEmail(TestCase): def test_send(self): subject = "Hello this is test mail" text = "Test, ignore it" from_mail = settings.EMAIL_HOST_USER to = [settings.EMAIL_HOST_USER] mail_fib = 'contacto.meteofib@gmail.com' self.assertEqual(mail_fib, from_mail) mail.send_mail( subject=subject, message=text, from_email=mail_fib, recipient_list=[mail_fib], fail_silently=False ) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Hello this is test mail') Running that i get the assertion error AssertionError: 'contacto.meteofib@gmail.com' != 'AKIAIX2J2YQBNVTGCONA' - contacto.meteofib@gmail.com + AKIAIX2J2YQBNVTGCONA When from my settings file I have: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'contacto.meteofib@gmail.com' EMAIL_HOST_PASSWORD = '123456789ABC' EMAIL_PORT = 587 -
How to make a price range filter with django using a slider
I'm trying to filter my products by price range using a slider .. I don't know how to connect the html with the views and the JavaScript.. this is my views.py : def prix(request): request.GET.get('value') return HttpResponseRedirect(request, 'produit/produits.html') product.html : <li>Prix <input id="ex2" type="text" class="span2" value="{% url 'boutique:prix' %}" onchange="callFun(this.value)" data-slider-min="0" data-slider-max="1000" data-slider-step="5" data-slider-value="[250,500]"/> <b>€</b> urls.py : url(r'^prix/$', views.prix, name='prix'), and this is the script that get the values: <script>function callFun(value) { fetch('prix/?value='+ value).then(function(response) { console.log(response.status); }) } my terminal says : [09/Jul/2017 12:51:35] "GET /boutique/produits/prix/?value=250,635 HTTP/1.1" 500 114372 it change with the slider values... -
DRF viewset overriding get_template_names throws ValueError
In this ticket from 2013 it is stated: The .action attribute will be set when inside a ViewSet, to whichever action is being triggered (eg. list). You can use this if you're inside a method eg get_template_names and need to get access to whichever action is being handled. However, when I try to conduct a simple experiment thus: class ExampleViewSet(viewsets.ModelViewSet): """ A viewset for the example model. """ queryset = Example.objects.all() serializer_class = ExampleSerialiser def get_template_names(self): if self.action == 'list': return ['example/list_examples.html'] With settings: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.TemplateHTMLRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework.renderers.JSONRenderer' ), } I get: Internal Server Error: /example/ Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 215, in _get_response response = response.render() File "/usr/local/lib/python2.7/dist-packages/django/template/response.py", line 109, in render self.content = self.rendered_content File "/usr/local/lib/python2.7/dist-packages/rest_framework/response.py", line 72, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/usr/local/lib/python2.7/dist-packages/rest_framework/renderers.py", line 174, in render return template_render(template, context, request=request) File "/usr/local/lib/python2.7/dist-packages/rest_framework/compat.py", line 279, in template_render return template.render(context, request=request) File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py", line 64, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "/usr/local/lib/python2.7/dist-packages/django/template/context.py", line 267, in make_context context.push(original_context) File "/usr/local/lib/python2.7/dist-packages/django/template/context.py", line 59, in push return ContextDict(self, *dicts, **kwargs) … -
Different outputs in local server and cloud server for keras weights
I have developed a django rest api which will recieve an image and return its corresponding class using neural networks. I have used keras for the neural network purpose. I used saved weights for classifying the images. I have created a ubuntu server in digital ocean for running it. When I run the django project in local server the output of the images are perfect. But when I deploy the project in digital ocean ubuntu server the output for every image comes same. Is there any specific reason for this? Here is my views.py code def index(request): return HttpResponse("Hello, world.") def api_test(request): return HttpResponse("One more step :)") def MODEL(image): img = cv2.imread(image) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) print(img.shape) img = cv2.resize(img, (56, 56)) if K.image_data_format() == 'channels_first': input_shape = (1, 56, 56) img = img.reshape(1, 1, 56, 56) else: input_shape = (56, 56, 1) img = img.reshape(1, 56, 56,1) img = img.astype('float32') img /= 255 model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(32, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.25)) model.add(Dense(60, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) model.load_weights('/root/projects/django_rest_api/rest_api/weight_current.hdf5') img_rows, img_cols = 56, 56 value = model.predict_classes(img) print(value[0]) return value[0] def … -
template does not exist error in django?
it renders the form correctly <div > <form method="post" action="{% url 'parts:stock_add_view'%}"> {% csrf_token %} {{ form }} <input type="submit"> </form> </div> but while rendering <div > <form method="post" action="{% url 'parts:stock_add_view'%}"> {% csrf_token %} {{ form.form_element }} <input type="submit"> </form> </div> but while rendering the single form field on submitting it shows template does not exist. I am using UpdateView to render the form class stock_add_view(CreateView): model = part_stock fields = ['part_id','entry_date','supplier','amount','remaining'] success_url = reverse_lazy('parts:part_list') in part_view_detail I am passing the form that is to be rendered in the part_detail_view class part_detail_view(DetailView): model = part_list context_object_name = 'part_detail' template_name = 'part_detail.html' def get_context_data(self, **kwargs): context = super(part_detail_view, self).get_context_data(**kwargs) context['my_list'] = populate_nav_bar() context['form'] = part_stock_form() return context -
Django CRUD operations for multiple records - transaction.atomic vs bulk_create
I have a Django 1.10 model, and a simple model: I have the following code: @api_view(['POST']) @transaction.atomic def r_test(request): for record in request.data: serializer = TestSerializer(data = record) if serializer.is_valid(): serializer.save() ...that takes 9 seconds (too slow) to execute for one 100 records. If I rewrite it the following way, it executes instantly. @api_view(['POST']) def r_test(request): obj_list = [] for record in request.data: obj = Test(field1 = record['field1']) obj_list.append(obj) Test.objects.bulk_create(obj_list) What bothers me is that I have read in many sources that wrapping function into a transaction (which I do by adding a decorator @transaction.atomic) would significantly improve insert operations in case of multiple operations. But I can't see this now. So the question is, does only bulk_create() deliver super-fast speed for inserting big data, or there's something I am doing wrong with transaction.atomic? Update: Moreover, I have ATOMIC_REQUESTS set to True in my settings. BTW, could it be that something is wrong in the settings? Like, say, Debug = True hinders Django from executing queries in a single transaction ? -
Upload image not saving
Views.py I can not really figure out what the problem is .I have been trying many otherways but no avail .Please help to sort out this little problem def user_account_dp(request): if request.method == "POST": modelform = modelformimage(request.POST,request.FILES,instance=request.user.userdp) if user_profile_pic_fm.is_valid(): user_profile_pic_fm.save() messages.success(request,'Successfully updated Profile') return redirect('gbiz1990:profile_account') else: messages.error(request,'chose a picture') else: user_profile_pic_fm =DpForm(instance=request.user.userdp) return render(request,"gbiz1990/user_account/user_profile.html",{'user_profile_pic_fm':user_profile_pic_fm}) html.file <form action='{{ action_url}}' method='post' enctype="multipart/form-data"> {{ user_profile_pic_fm.profilepic}} {% csrf_token %} <button type="submit">Save changes</button></form> -
django no matching url with parameters
When the login process is complete, I am trying to redirect the user to their profile page, I am passing the user id to the url, although I get the below error. Reverse for 'index' with arguments '(2,)' not found. 1 pattern(s) tried: [u'profiles/profile/(?P/d+)/$'] login redirect return redirect('profiles:index',user.id) url expression url(r'^profile/(?P<user_id>/d+)/$', views.index, name='index'), -
Process exited with status 127, error code=H10 desc=“App crashed”
I am trying to deploy on Heroku my project in Docker with Angular 4 frontend, Django backend and postgresql database. At this moment my files look as shown below. I am note sure if this is done properly? I pushed it using heroku container:push web --app myproject but it doesn't work (Logs). I noticed that in logs there is Process exited with status 127. I have found here 127 Return code from $? that Value 127 is returned by /bin/sh when the given command is not found within your PATH system variable and it is not a built-in shell command. In other words, the system doesn't understand your command, because it doesn't know where to find the binary you're trying to call. Besides, when I was trying different commands I very often were getting error like /bin/sh: 1 not found what I described in this post. To sum up, it seems to me that it may be root of the problem. Any suggestions how can I solve it? Logs: 2017-07-08T13:19:48.882112+00:00 heroku[web.1]: Process exited with status 0 2017-07-08T13:20:40.336825+00:00 heroku[run.9745]: Awaiting client 2017-07-08T13:20:40.395900+00:00 heroku[run.9745]: Starting process with command `docker-compose up` 2017-07-08T13:20:40.542168+00:00 heroku[run.9745]: State changed from starting to up 2017-07-08T13:20:45.727667+00:00 heroku[run.9745]: State changed … -
Django Pagination always returns "That page number is less than 1"
I am new to Django and trying to get the Pagination system to work. Whatever I do I get the error when the page attempts to render. It is the return render line that is raising the error in the view.py code. Exception Type: EmptyPage Exception Value : That page number is less than 1 I have checked the pagination object that is being passed to the renderer. It says "< Page 1 of 26>". scoresPaginator.object_list shows the correct data objects. Print statements in the code all return the expected values. I have removed all code from the template so there should be no problem there. All is does now is print a title. I have updated the pagination module to the latest version. The reason for the POST data collection is when the Pagination is working I intend to refer to it using jQuery post. All scripts have been commented out in the template as well. My code in views.py is: if request.method == 'POST': limit = int(request.POST.get('numberPP')) arrange = request.POST.get('arrangeBy') pageNumber = request.POST.get('pageNumber') else: limit = 10 arrange = 'id' pageNumber = 1 rawScores = score.objects.filter(userID=request.user).order_by('-'+arrange) scoresPaginator = Paginator(rawScores,limit) try: pScores = scoresPaginator.page(pageNumber) except PageNotAnInteger: pScores = scoresPaginator.page(1) … -
Python Django migration error
django.db.utils.OperationalError: (1553, "Cannot drop index 'star_ratings_userrating_user_id_5a83a88db79dd2cf_uniq': needed in a foreign key constraint")[![enter image description here][1]][1] I have installed an application in my project django-star-ratings 0.5.3. It requires syncing database and when I migrate python manage.py migrate it shows an error. How can I resolve this issue? -
Access management with magnetic card (badges) in Django
I need to develop a university project in Django but I have a problem I can not solve: I'm developing a Django application for access management in a lab. Specifically, a user can access the lab after swipes the badge. Then I should create a small server to which POST requests are made (in JSON format, indicating person ID and input time). But I do not know how to do it, I have no ideas as I'm new to Django and Python. Can anyone help me to please? -
Serializing ManyToManyField in DjangoRestFramework
I have 2 models here Tag and Question class Question(models.Model): question = models.TextField(blank=False, null=False) question_image = models.ImageField(blank=True, null=True, upload_to='question') opt_first = models.CharField(max_length=50, blank=False, null=False) opt_second = models.CharField(max_length=50, blank=False, null=False) opt_third = models.CharField(max_length=50, blank=False, null=False) opt_forth = models.CharField(max_length=50, blank=False, null=False) answer = models.CharField(max_length=1, choices=(('1','1'),('2','2'),('3','3'),('4','4'))) description = models.TextField(blank=True,null=True ) tag = models.ManyToManyField(Tag) created_on = models.DateTimeField(default= timezone.now) class Tag(models.Model): name = models.CharField(max_length = 50, null=False, unique=True) And I have serializers classes for these two models class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name',) class QuestionSerializer(serializers.ModelSerializer): # tag = TagSerializer(many=True) def to_representation(self, obj): rep = super(QuestionSerializer, self).to_representation(obj) rep['tag'] = [] for i in obj.tag.all(): # rep['tag'].append({'id':i.id,'name':i.name}) # Below doesn't give JSON representation produces an error instead rep['tag'].append(TagSerializer(i)) return rep class Meta: model = Question fields = ('question', 'question_image', 'opt_first', 'opt_second', 'opt_third', 'opt_forth', 'answer', 'description', 'tag') read_only_fields = ('created_on',) Here on using TagSerializer in the to_repesentation method of QuestionSerializer doesn't serialize the tag object. Instead produces error ExceptionValue : TagSerializer(<Tag: Geography>): name = CharField(max_length=50, validators=[<UniqueValidator(queryset=Tag.objects.all())>]) is not JSON serializable -
you are trying to add a non-nullable field 'description' to wine without a default
I tried to add a description column and i tried to make changes in models.py. However, when I was trying to migrate I get this error C:\Users\Adhista Chapagain\Desktop\winerama>python manage.py makemigrations You are trying to add a non-nullable field 'description' to wine without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: models.py code looks like this: from django.db import models import numpy as np class Wine(models.Model): name = models.CharField(max_length=200) images = models.ImageField(null = True, blank=True) description = models.CharField(max_length=200) and code for load_wine def save_wine_from_row(wine_row): wine = Wine() wine.id = wine_row[0] wine.name = wine_row[1] wine.images = wine_row[2] wine.description = wine_row[3] wine.save() -
Tracking changes in Django with PostgreSQL
I have a Django project with PostgreSQL as database. There are few tables that describe state (let's call them "state tables") There are several servers that can modify state (Each one modifies its own table) There is one server that reads the state (let's call it"reader") and modifies internal stuff based on current state of the tables. What I'd like to do is to give the reader ability to know what row in state tables was changed, so that it won't have to scan all the tables all the time. Currently I have a special tracking table and a post_save() trigger on all state tables. The post_save trigger saves the table name and the ID. Initially the plan was to define sequence ID on the tracking table and to check whether "last known tracking ID" is the largest. If it's not - I would scan all of the tracked entries and know what states were changed. However, it seems that PostgreSQL's indexes are not promised to be sequential. I don't mind the gaps between them, but I do rely on tracking record N+1 to have ID bigger than record N. Any advice? -
how can i pass context data in django after ajax request
class stock_update_view(UpdateView): model = part_stock fields = ['part_id','entry_date','supplier','amount','remaining'] success_url = reverse_lazy('parts:part_list') template_name = 'part_detail.html' def get_context_data(self, **kwargs): context = super(stock_update_view, self).get_context_data(**kwargs) context['update_form'] = context.get('form') return context def get(self, request, *args, **kwargs): return render(request, 'part_update.html',{'hi':'hi','update_from': }) after ajax request$("#my_form").load(url to sock_update_view calss); how can i return context['update_form'] = context.get('form') the update_form so that i will get form pre-filled -
Destroy session or cookie in django when user get offline
I have a website and i want to destroy some session or cookie in django when user discoonet suddenly or get offline (wifi discoonect or disconnect mobil data). But i dont know to how do this! Is there any default library to do this? -
Pycharm django configuration removed on git pull
I have my Django project repo on github. My problem is whenever I take a pull request ,my Pycharm project configuration gets deleted. -
Want to know that how to get the data from the user in django and submit it to database
I am new to django and started a small project.I have made this form template in bootstrap named 'signup.html' <!DOCTYPE html> <html> <head> <title>Home Page</title> {% load static %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css"/> <link rel="stylesheet" href="{% static 'css/bootstrap-theme.min.css' }" type="text/css"/> <style> .login-form-window { box-shadow: 2px 1px 3px 2px rgba(0,0,0,0.2); min-height:100%; padding:80px; box-sizing: border-box; } .input-group{ margin:20px; } </style> </head> <body> <div class="row"> <div class="col-md-4"> </div> <div class="col-md-4 login-form-window"> <form name="login_form"> <div class="input-group input-group-lg"> <span class="input-group-addon" id="sizing-addon1">@</span> <input type="text" class="form-control" placeholder="username" aria-describedby="sizing-addon1"> </div> <div class="input-group input-group-lg"> <span class="input-group-addon" id="sizing-addon1">@</span> <input type="password" class="form-control" placeholder="password" aria-describedby="sizing-addon1"> </div> <div class="input-group input-group-lg"> <input type="button" class="btn btn-lg btn-primary" value="Log In" name="login_button"/> </div> </form> <br /><br /> Don't have any account <b><a href="{% url 'signup' %}"/>Sign Up</a></b> now. </div> </div> </body> </html> And then i have created a models.py which will create a table in the database. from django.db import models class user_details(models.Model): user_name=models.CharField(max_length=30) user_email=models.CharField(max_length=30) user_password=models.CharField(max_length=30) Now i am not understanding how to get the data entered by the user in form and then submit it to the database. I have seen some examples, i am not understanding that if i have to create a form.py file or views.py to submit the data into … -
django how to join table in multi databases using saw sql?
I need to join table in diffrent database to perform sql query but when I read the django doc about performing raw sql query it gives me a cursor from connection from django.db import connection with connection.cursor() as cursor cursor.execute(mysql query) i mean the cursor is from only one database if the raw sql query need to use two db. will it work? i assume the two databse got the same username and password. -
How to parse application/x-www-form-urlencoded recieved via POST
I'm writing a django webhook for a service that send data via POST in what I believe is the application/x-www-form-urlencoded format. Example POST show below: POST id=a5f3ca18-2935-11e7-ad46-08002720e7b4 &originator=1123456789 &recipient=1987654321 &subject=MMS+reply &body=View+our+logo &mediaUrls[0]=https://storage.googleapis.com/mms-assets/20170424/a0b40b77-30f8-4603-adf1-00be9321885b-messagebird.png &mediaContentTypes[0]=image/png &createdDatetime=2017-04-24T20:15:30+00:00 I understand how to parse json but I haven't encountered this format before. There doesn't appear to be any userful tutorials for how to handle this via POST. I'm stuck at this point so help would be greatly appreciated. -
error during django template rendering
working in django tutorials and this error in template rendering appears NoReverseMatch at /music/1/ Reverse for 'favorite' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] this is a detailed view for the problem Error during template rendering In template E:\Codes\bucky - Django Tutorials for Beginners\website\music\templates\music\detail.html, error at line 10 Reverse for 'favorite' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] 1 <img src="{{ album.album_logo }}"> 2 3 <h1>{{ album.album_title }}</h1> 4 <h2>{{ album.artist }}</h2> 5 6 {% if error_message %} 7 <p><strong>{{ error_message }}</strong></p> 8 {% endif %} 9 10 <form action="{% url 'music:favorite' album.id %}" method="post"> 11 {% csrf_token %} this is my music/urls.py app_name = 'music' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<album_id>[0-9]+)/$', views.detail ,name='detail'), url(r'^(?P<album_id>[0-9]+)/favorite/$', views.favorite ,name='favorite'), ] the detail.html file where the error appear in the form <img src="{{ album.album_logo }}"> <h1>{{ album.album_title }}</h1> <h2>{{ album.artist }}</h2> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form action="{% url 'music:favorite' album.id %}" method="post"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{ forloop.counter }}" name="song" value="{{ song.id }}"> <label for="song{{ forloop.counter }}"> {{ song.song_title }} {% if song.is_favorite %} <img src="http://i.imgur.com/b9b13Rd.png"> {% … -
Django - Making add to cart - need complete help - not deleting an instance when removed from add to cart
I want to create a site that sells glasses. This site must have the functionality of ADD TO CART as many online ecommerce sites do. Following are the things I want: The user can add as many items as he wants to the cart There must be a DELETE functionality so that anyone can empty the cart at will The deleted items must not be deleted from the main database, so the instances must be copied while adding to the cart def cart_a_glass(request, pk): a1 = 0 glass=get_object_or_404(Glass, pk = pk) allcartglasses=carting.objects.all() for gla in allcartglasses: if gla.user == request.user: a1= a1 + gla.glass.price * gla.cartnovalue if request.method == 'POST': form = CartGlassForm(request.POST, pk=pk, subtotal=a1) # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned_data as required (here we just write it to the model due_back field) m2 = carting(id=pk+str(request.user.id),user=request.user,glass=glass,cartnovalue=form.cleaned_data['Cartno'],cartdate=datetime.date.today()) m2.pk = None m2.save() # redirect to a new URL: return HttpResponseRedirect(reverse('my-cart') ) else: proposed_number = 3 form = CartGlassForm(initial={'Cartno': proposed_number},pk=pk, subtotal=a1) return render(request, 'catalog/cart_a_glass.html', {'form': form, 'glass':glass}) def delete_from_cart(request, pk): glass=get_object_or_404(Glass, pk = pk) allcartglasses=carting.objects.all() if request.GET.get('delete'): allcartglasses.delete() return HttpResponseRedirect(reverse('to-delete')) return redirect('catalog:to-cart') This is my urls.py urlpatterns += [ url(r'^glass/(?P<pk>\d+)/cart$', views.cart_a_glass, name='to-cart'), ] urlpatterns …