Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Free api in json for hotel booking
I am working on developing a hotel booking website , for that i need an API to display the hotel information on different areas. I have searched a lot in the web but didn't find any free one in JSON. So, please give a reference to API. I am using django framework to develop that site. -
How to render a POST and make it show up on another page? in Django form
I'm trying to create Car Rental website similar to Hyrecar. I created a form according to the Django tutorial "Working with forms", but I don't know how to render information I got from the POST forms. I want to make information(Booking Name,rental price ...etc) that I got from POST show up on another page like this. I want to redirect it to the page pop. if the user booked a car and post the form . after that redirect it to the pop.html page and show the booking detail that the user posted now . Forms.py class BookingForm(ModelForm): class Meta: model = Booking widgets = { 'times_pick': forms.TimeInput(attrs={'class':'timepicker'}), } fields = ('booking_name','rental_price','book_car','customer_name','times_pick',) urls.py [ url(r'^booking/',views.BookingView.as_view(),name='car_booking'), url(r'^pop/$',views.PopView.as_view(),name='pop'), ] views.py class BookingView(FormView): template_name = 'buggy_app/booking.html' form_class = BookingForm models = Booking def form_valid(self, form): form.save() return super(BookingView, self).form_valid(form) success_url = reverse_lazy('index') def get_context_data(self, **kwargs): # kwargs['car'] is the car booking now! try: kwargs['car'] = Car.objects.get(id=self.request.GET.get('car', '')) except (Car.DoesNotExist, ValueError): kwargs['car'] = None return super(BookingView, self).get_context_data(**kwargs) def get_initial(self): initial = super(BookingView, self).get_initial() if 'car' in self.request.GET: try: initial['book_car'] = Car.objects.get(id=self.request.GET['car']) except (Car.DoesNotExist, ValueError): pass return initial booking.html <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class='btn btn-primary' value="Submit"> </form> -
Django schema design: Am I creating redundant rows/relationships?
I received a warning on Heroku that I'm nearing my row limit (10,000) after doing the first import in my app. I've inspected my database schema and rows per table: schemaname | relname | n_live_tup ------------+----------------------------------+------------ public | core_releasegroup | 5997 public | core_artist_release_groups | 5928 public | django_session | 199 public | core_artist | 134 public | core_subscription | 134 public | core_pendingaddition | 67 The numbers are not identical because the query I used utilizes an "estimate", but the overall numbers add up. Here are my models.py relevant files: class ReleaseGroup(BaseModel): mbid = models.CharField(max_length=36, unique=True) title = models.CharField(max_length=512) type = models.CharField(max_length=512) release_date = models.DateField(blank=True, null=True) class Artist(BaseModel): users = models.ManyToManyField('accounts.UserProfile', through="Subscription") release_groups = models.ManyToManyField(ReleaseGroup) mbid = models.CharField(max_length=36, unique=True) name = models.CharField(max_length=512) sort_name = models.CharField(max_length=512) disambiguation = models.CharField(max_length=512, null=True) I don't really see anything wrong with my models specifications, but perhaps a more seasoned Djangoist can chime in? -
Improve the django poll app
I already replicated the django tutorial for the poll app but i want to make further functionality , I want users to be able to create polls through a form in the template , Any help or documentation will be helpful. What i have already followed -
Use variable to slice loop in django template
I'm trying to slice loop in django template with variable USUAL WAY {% for article in module.module_article_key.module_article_category.article_category_key.all|slice:":2" %} {{ article.article_title }} {% endfor %} WHAT NEEDS {% for article in module.module_article_key.module_article_category.article_category_key.all|slice:":module.module_article_key.module_article_category" %} {{ article.article_title }} {% endfor %} so we have working variable {{ module.module_article_key.module_article_category }} normaly this variable gives integer value stored for this module, however wen i use it to slice loop - nothing happens -
how use object.filter and calculate all integerfiled
i need help :( I have django(2.0) models : product and vendor_name class vendor_name(models.Model): name = models.CharField(verbose_name='name vendor', max_length=256) version = models.CharField(verbose_name='version vendor', max_length=256) class product(models.Model): name = models.CharField(verbose_name='name product', max_length=256) vendor = models.ForeignKey(vendor_name, verbose_name='vendor', blank=True, null=True, default=None, on_delete=models.SET_NULL) lic = models.PositiveSmallIntegerField(verbose_name='lic', default=0) Example___ first record: product.name = AAA vendor.name = ZOO vendor.version = 6 lic = 27 second record: product.name = BBB vendor.name = ZOO vendor.version = 6 lic = 500 how use object.filter where vendor.name ZOO and vendor.version 6, calculate all product lic ? I want see: 527 and i add new record product.name = CCC vendor.name = ZOO vendor.version = 6 lic = 500 lic = 1027 and i not export site {{ product.lic }} but why ? help me please ! -
Error: MagickWand shared library not found. You probably had not installed ImageMagick library. (even though I have)
I've installed Imagemagick and wand however I get this error message when trying to start my django server: ImportError: MagickWand shared library not found. You probably had not installed ImageMagick library. Try to install: brew install freetype imagemagick so I perform brew install freetype imagemagick and then it responds with: Warning: freetype 2.9.1 is already installed and up-to-date To reinstall 2.9.1, run `brew reinstall freetype` Warning: imagemagick 7.0.8-2 is already installed and up-to-date To reinstall 7.0.8-2, run `brew reinstall imagemagick` so I perform brew reinstall imagemagick and then it returns the original error: ImportError: MagickWand shared library not found. You probably had not installed ImageMagick library. Try to install: brew install freetype imagemagick and this cycle continues. Any idea what the problem is? -
How to connect to MsSQL server with Django
I am struggling with connecting to my local MsSQL server with Django. It says when I make command 'makemigrations': django.core.exceptions.ImproperlyConfigured: 'sqlserver_ado' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' My settings: DATABASES = { 'default': { 'NAME': 'TestDB', 'ENGINE': 'sqlserver_ado', 'HOST': 'STEPAN', 'USER': '', 'PASSWORD': '', } } In this solution: Setting up django-mssql issues I found that my 'sqlserver_ado' should be in the same folder 'site-packages', which it is (Python IDLE shell): >>> import sqlserver_ado >>> sqlserver_ado <module 'sqlserver_ado' from 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\lib\\site-packages\\sqlserver_ado\\__init__.py'> >>> import django >>> django <module 'django' from 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\lib\\site-packages\\django\\__init__.py'> I have a PyWin32 installed and importing in IDLE is fine (even the path is fine), yet still I get this error message. Any ideas or advices? Spec: Win10, Python 3.6, Visual Studio 2017, django-mssql 1.8, django 2.0.6, MsSQL (developer) and this DB is present (with flask I have no problem to connect to my local server [just for comparsion my connection string in another flask project: SQLALCHEMY_DATABASE_URI = "mssql+pyodbc:///?odbc_connect={}".format(urllib.parse.quote_plus( "DRIVER={SQL Server};Server=STEPAN;Database=TestDB;Trusted_Connection=yes;")) ]), project was automaticly created by Visual Studio, command that throws this error: python manage.py makemigrations -
.on('mouseover') did not feedback info
I have such a snippet of ajax request: <div> <h4>Comments</h4> <!-- <form action="/article/comment/create/{{ article.id }}" method='post'> --> <form action="#"> <textarea class="form-control" rows="5" name='comment' id="commentContent"></textarea> <br> <button class="btn btn-primary" id="commentBtn">Post Your Comment</button> </form> </div> </div><!--/class="col-xs-8 col-md-8">--> </div><!-- row --> <script src="/static/js/jquery-3.3.1.js"></script> <script src="/static/js/jquery-csrf.js"></script> <script> $(document).ready(function(){ var article_id = article.id; var num_pages = {{ page.num_pages }}; $("#commentBtn").on('mouseover', function(e){ e.preventDefualt(); alert("clicked") var comment = $("#commentContent").val(); var param = { "article_id": article.id "content": comment}; $post("/comment/create/", param, function(data){ var ret = JSON.parse(data); if (ret["status"] = "ok") { $("#commentConent").val(""); window.location.href = "/article/detail/{{ article.id }}?page_number=" + num_pages; } else { alert(ret["msg"]); } }); }); }); </script> I set the event type as mouseover, However, when I place my mouse over the button "#commentBtn", nothing occurs. What's the problem it might be with my codes? -
regular expression not work when sending paramter
i use django 1.1 and python 3.6, i make view show detail for one product but when i send id for product to view it not work but when i change in urlpatterns the regular expression to be different with products list view it work. example:(not working code) urlpatterns = [ url(r'^products/', productslistview.as_view()), url(r'^products-f/', product_list_view), url(r'^products/(?P<pk>\d+)/$', productdetailview.as_view()), url(r'^products-f/(?P<pk>\d+)/$', product_detail_view), ] and when i changed to(working code) url(r'^products-d/(?P<pk>\d+)/$', productdetailview.as_view()), url(r'^products-f-d/(?P<pk>\d+)/$', product_detail_view), -
Adding A Function To Django Built-in Login
My Question is How I can Add A Function To Django Built-in Login I want To Add get_absolute_url() Function In User Built-in Model Models.py from django.contrib.auth.models import User from django.shortcuts import render, redirect, get_object_or_404 class PostLikeToggle(RedirectView): def get_redirect_url(self, *args, **kwargs): slug = self.kwargs.get("username") obj = get_object_or_404(User, username=slug) return obj.get_absolute_url() -
Django DetailView
i am a beginner in Django. i have the below simple django model (refer to below). My list view has worked perfectly fine in the https://localhost/simpleapp/. However, when i try DetailView via https:local host/simpleapp/1, it gives me a 404 cant found. I don't know where is the problem as i already defined the urls wit the regular expression ^(?P\d+)/$. Model.py class University(models.Model): university_name = models.CharField(max_length = 50) def __str__(self): return self.university_name class Student(models.Model): last_name = models.CharField(max_length = 50) first_name = models.CharField(max_length = 50) age = models.PositiveIntegerField() university = models.ForeignKey(University, on_delete=True) def __str__(self): return '{} {}'.format(self.first_name, self.last_name) Views.py class StudentList(generic.ListView): model = models.Student context_object_name = 'student_list' template_name = 'simpleapp/student_list.html' class StudentDetail(generic.DetailView): model = models.Student context_object_name = 'student_detail' template_name = 'simpleapp/student_detail.html' urls.py in app folder urlpatterns = [ url(r'^$', views.StudentList.as_view(), name='student_list'), url(r'^(?P<pk>\d+)/$', views.StudentDetail.as_view(), name='student_detail'), ] urls.py in project folder urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', views.Index.as_view(), name='index' ), url(r'^simpleapp/$', include('simpleapp.urls', namespace='simpleapp')), ] student_detail.html {% extends 'simpleapp/student_base.html' %} {% block content %} <h1> {{student_detail}}</h1> {% endfor %} {% endblock %} -
Application error : always 503 is return
I want to move my Django application in Heroku.git push heroku master & heroku ps:scale web=1 & heroku open is successful, but when I go to my page https://xxxxxxxxx.herokuapp.com, Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. error happens. When I run heroku logs, 2018-06-24T08:55:18.004452+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=xxxxxxxxx.herokuapp.com request_id=2e6dfc7f-9685-4732-a51f-7d35d12cc103 fwd="xxxxxxxxx" dyno= connect= service= status=503 bytes= protocol=https 2018-06-24T08:56:21.396018+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=xxxxxxxxx.herokuapp.com request_id=f9229ca1-5e28-451a-91c3-7ad062d4a4fe fwd="xxxxxxxxx" dyno= connect= service= status=503 bytes= protocol=https 2018-06-24T08:56:22.816116+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/admin" host=xxxxxxxxx.herokuapp.com request_id=5be36c68-2873-4399-808b-fe7b4ada8fca fwd="xxxxxxxxx" dyno= connect= service= status=503 bytes= protocol=https 2018-06-24T08:56:24.026167+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/admin" host=xxxxxxxxx.herokuapp.com request_id=c907049a-b0c8-4c1f-bd27-81344c1850d4 fwd="xxxxxxxxx" dyno= connect= service= status=503 bytes= protocol=https 2018-06-24T08:56:27.210655+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/admin/" host=xxxxxxxxx.herokuapp.com request_id=694e7487-749f-45b1-bb34-b131485546da fwd="xxxxxxxxx" dyno= connect= service= status=503 bytes= protocol=https 2018-06-24T08:56:36.931801+00:00 app[api]: Scaled to web@0:Free by user xxxxxxxxxxxxxxxxxx@gmail.com 2018-06-24T08:56:37.066921+00:00 heroku[web.1]: State changed from crashed to down I really cannot understand why 503 error happens.I stop Heroku,and restart it, but same error happens.What is wrong in my settings?How should I fix this? -
Slow REST API: How to cache data and simplify querying?
I'm accessing a rest API which allows some CRUD operations on relational data (e.g. cars and their tires). However, this API is very slow and only has very limited filtering capabilities. Therefore, in order to make data access faster and querying easier, I was thinking to replicate the data into my own relational DB, and then use a nice ORM to access it. The amount of data is not insane (a few thousands of cars), thus this should be perfectly viable. However, now I need a nice way of synchronizing the data between the two sources (REST API and my DB). Right now, I intend to use Django's ORM and I would be very interested in your design recommendations, how to implement a nice synchronization architecture. Thank you, Alex -
Django uploaded images come up too big on the pages
i am a django learner, i went through what's in the "Python crash course" book and currently making really simple website just to memorise what's after what and get more familiar with the basics. Can someone explain to me why the images I upload come up enormously big on the pages or how to fix that, please. I couldn't really find anything like that so far Don't pay attention to the rubbish writings on there. It's just about a german shepherd. Complicated relationship[That's how images look like when I open the webpage[]1[1] -
Cannot resolve keyword 'user' into field. Choices are: document, id, password, username, username_id
Something is wrong with my models,or in the way I am trying to implement my algorithm. models.py class Profile(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE) password = models.TextField(max_length=80,blank=True) class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d') uploaded_by = models.ForeignKey(Profile,on_delete=models.CASCADE) date_uploaded = models.DateTimeField(auto_now_add=True) Upload function(views.py) @login_required def upload(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) profile = Profile.objects.get(user = request.user) newdoc.uploaded_by = profile.request.user newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('upload')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return render(request,'upload.html',{'documents': documents, 'form': form}) I got fielderror at upload Cannot resolve keyword 'user' into field. Choices are: document, id, password, username, username_id It points to line 57 profile = Profile.objects.get(user = request.user) Is it possible to get more information form shell? This works so far In [3]: user = User.objects.get(username='drazen75') In [6]: user.last_login Out[6]: datetime.datetime(2018, 6, 24, 7, 1, 2, 196411, tzinfo=<UTC>) How to fix this? -
Django Based User Application Management
I have created a Admin Login Portal. Admin can Create, Update, Read , Delete Users as well as Departments (like Software,Hardware, Marketing, HR etc) How to authenticate other User Authentication using email and they should have access to edit only department field. User Profile Contains : Name Address Contact No Designation Departments Note: User should have access only that particular Department assign by Admin I am a beginner in Django can anyone please help me with this. -
Django, fetching data of other users
First of all, I am sorry for not uploading my code. I currently do not have my pc as I am on vacation and didn’t take my pc with me. Anyways, I used django’s built in authentication system to create log in, sign up and log out. Now what I would like to do is have the ability to change your bio (which I figured out how to do on web) and other users can view that bio through your profile page. e.g /home/usernametosearch Currently I’ve only figured out how to fetch data such as your username from the account that you are logged on to. Not data from other users. Can someone tell me how I can do that please? I am a beginner Thanks! -
How to know if a user arrived at the login page after clicking a logout? Django
I am using the django's built-in auth module for user authentication. urls.py url(r'^accounts/logout/', auth_views.logout, kwargs={'next_page': reverse_lazy('login')}), url(r'^accounts/login/', auth_views.login, name='login', kwargs={'redirect_authenticated_user': True,"authentication_form":CustomAuthForm}), The user is redirected to login page immediately after logout. But I need to display a "signed out!" message to the user in the login page. How would I know whether a user clicked the logout link to arrive at login page or he/she directly visited login(in this case I won't show any message). -
Where I can find good tutorials for building a cms using django
I finished couple of tutoials about django framework. Where can I find good place for tutoruals the teach me how to build cms using django from scratch. -
Get similar objects of same type from django taggit
I am using django-taggit tags in two models, lets say Model1 and Model2. I am using below code to get similar objects from my one of the model. obj1 = Model1.objects.get(pk=1) similar = obj1.tags.similar_objects() In the similar objects I am getting Model2 objects also. So How to get only Model1 similar objects. -
Djang ImageField - render only the <input> element
I have a Django form which has an ImageField in it, and I render the field like this in my template: {{ form.my_image_field }} The resulting HTML looks like this: Currently: <a href="https://....s3.amazonaws.com/....jpg">....jpg</a> <input name="my_image_field-clear" id="my_image_field-clear_id" type="checkbox"> <label for="my_image_field-clear_id">Clear</label><br> Change: <input name="my_image_field" id="id_my_image_field" type="file"> I want to render only the <input element, since I am using the bootstra-fileinput library: https://www.npmjs.com/package/bootstrap-fileinput : <input name="my_image_field" id="id_my_image_field" type="file"> Is it possible to do this without writing the <input> tag manually in the template? -
adjust cart session along with the cart models
Adding the items to the cart is very crucial. I have a session based shopping cart and I need to adjust that shopping cart along with the model because I will need the cart data or cart items in the database either. Here is the models for the cart models.py class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE) items = models.ManyToManyField(Variation, through='CartItem') quantity = models.PositiveIntegerField(default=1) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) subtotal = models.DecimalField(max_digits=50, decimal_places=2, default=0.00) tax_percentage = models.DecimalField(max_digits=10, decimal_places=5, default=0.085) tax_total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00) total = models.DecimalField(max_digits=50, decimal_places=2, default=0.00) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) item = models.ForeignKey(Variation, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) line_item_total = models.DecimalField(max_digits=10, decimal_places=2) carts.py CART_ID = 'cart-id' class Cart(Object): def __init__(self, request): """ Initialize the cart """ self.session = request.session # get the current session from request.session.get(CART_ID) cart = self.session.get(CART_ID) if not cart: # cart is not present in the session # save an empty cart in the session # but we expect our cart dictionary to use product ids as keys # and a dictionary with quantity and price as value for each key # by that we can gurantee same product is not added twice cart = self.session[CART_ID] = {} else: … -
Import column from another table
I made API with Django Restframework. [models.py] from django.db import models class Article(models.Model): article_no = models.AutoField(primary_key=True) content = models.CharField(max_length=500, null=False) password = models.CharField(max_length=20, null=False, default='1234') date = models.DateTimeField(auto_now_add=True) class Comment(models.Model): article_no = models.ForeignKey('Article', on_delete=models.CASCADE) content = models.CharField(max_length=50, null=False, default='') password = models.CharField(max_length=20, null=False, default='1234') date = models.DateTimeField(auto_now_add=True) [views.py] class ArticleDetail(APIView): def get(self, request, article_no, format=None): try: article = models.Article.objects.get(article_no=article_no) serializer = serializers.ArticleDetailSerializer(article) return Response(status=status.HTTP_200_OK, data=serializer.data) except models.Article.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) [urls.py] urlpatterns = [ path('article/<int:article_no>', views.ArticleDetail.as_view(), name='article_detail'), ] [serializers.py] class ArticleDetailSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True) comment = CommentSerializer(many=True, read_only=True) class Meta: model = models.Article fields = ( 'article_no', 'content', 'password', 'date', 'comment', ) In serializers.py, I defined comment = CommentSerializer(many=True, read_only=True) and add it to fields. And to test it, I add comment for article_no=1 But When I connect to /article/1, comment doesn't show anything. I want to show all comments related it's article_no. How can I fixed it? Thanks. -
Ajax request not working properly in django
JS code for ajax request <script type="text/javascript"> $(document).ready(function(){ console.log("IN") var cartUpdateForm = $('.js_cart_update_form') cartUpdateForm.submit(function(event){ event.preventDefault() var thisform = $(this); var method = thisform.attr("method"); var api = thisform.attr("api"); var data_ = thisform.serialize(); var current = window.location.href console.log(method,api,current,data_) $.ajax({ url:api, data:data_, type:method, success:function(data){ console.log("success") console.log(data) update_table(data) }, error:function(data){ console.log('error') } }); function update_table(data){ table_ = $('.js_cart_table') table_body_ = table_.find(".js_cart_body") table_body_.html("") remove_form = $(".js_remove_form") if(data.items.length > 0){ $.each(data.items , function(index , val){ var rmf = remove_form.clone() rmf.css('display','block') rmf.find(".cart_item_id").val(val.id) table_body_.prepend("<tr><td>"+val.name+"</td> <td>"+val.price+"</td><td>"+rmf.html()+"</td></tr>") }); } else { console.log("reloading..") window.location.href = current } } }); }); </script> updateapi in views.py: def update_util(request): pk = int(request.POST.get('item_id')) rest_id = request.session['rest_id'] restaurant = Restaurant.objects.get(pk = rest_id) cart_obj = Cart.objects.new_or_create(request) remove = request.POST.get('remove') item = FoodItem.objects.get(pk=pk) # print(pk) if remove == '1': cart_obj.items.remove(item) else: cart_obj.items.add(item) def update(request): update_util(request) rest_id = request.session['rest_id'] return redirect(reverse('restaurant:menu', kwargs={'pk':rest_id})) def updateapi(request): if request.is_ajax(): update_util(request) cart_obj = Cart.objects.new_or_create(request) print(request.POST.get('remove') ,'called') items = [] data = {} for item in cart_obj.items.all(): items.append({'name':item.name , 'price':item.price ,'id':item.id}) data_ = {'items':items , 'total':cart_obj.total , 'subtotal':cart_obj.subtotal} return JsonResponse(data_) HTML Form on which call is occuring for remove: <table class="table js_cart_table"> <thead> <th>Item</th><th>Price</th><th></th> </thead> <tbody class="js_cart_body"> {% for item in cart.items.all %} <tr><td>{{ item }}</td> <td> {{ item.price }}</td> <td>{% include 'cart/include/remove_cart.html' with …