Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to implement multiple request values for single field in django
With this curl command I am requesting for only "Books" for field "ProductName" curl -X POST http://localhost:8000/Productfilter/ -d '{"ProductName":"Books"}' -H "Content-Type:application/json" def Productfilter(self, request, format=None) queryset = Model.objects.filter(ProductName=request['ProductName']) ser = ModelSerializer(queryset, many=True) for item in ser.data: sendData.append({"ProductUrl": item['ProductUrl']}] return sendData I want to implement for multiple request values for same field. Like I want something like this---> curl -X POST http://localhost:8000/Productfilter/ -d '{"ProductName":"Books","Pencil","Copy"}' -H "Content-Type:application/json" Please suggest the curl command for this type of requests and what modification to be done in coding of def Productfilter. -
Running Separate Python program with Django Channels
I am new to Using Django and was wondering if anyone could help me out. I currently have a python program that does some image processing and can then sends the frame via a tcp connection. I want to use a Django server with channels to send those processed image frames to clients via the web-socket group mechanism provided by Django channels. My idea is to set up a tcp connection from Django to my other python program and have Django push the image frames to the clients every time it receives one. My question is how can I get Django to create a separate process that will receive data from my other program and push it to the clients on the group channel from with my consumers.py file? If not then can I somehow use Django signals to detect when data is received from my other python program? Any better suggestions for doing what I want are also welcome. Thank you, Ariel -
Is Django the right choice for my simple Webapp?
I began learning Python and wrote a fairly simple program that prints the current distance of earth to every other planet in the solar system. (Yay Astropy!) Now i want to create a Website that visualizes these calculations in realtime: I want to update the distance every second or so. My Question is: What is the easiest, most elegant way to take those values out of python and display them in HTML? Render the site directly with a Python framework? I have a clue that Django might be a bit oversized for this. Or write the value into a JSON or CSV and read it with Javascript? How would more experienced Developers implement this? -
Django - Remove Unique Constraint from a field
I have a model like class LoginAttempts(models.Model): user = models.OneToOneField(User, unique=False) counter = models.IntegerField(null=True) login_timestamp = models.DateTimeField(auto_now=True) The table created in db is like However If I create another entry with user_id = 362 it fails with IntegrityError: duplicate key value violates unique constraint. Id is already my primary key, I want to have same user having different counters instead of creating a new table referencing them since this is simple table. How to achieve the same or what what could be the best way. I want to restrict user to some specified number of failed logins. -
Get all the fields 2 times on web page
My models.py file contain different field name then forms.py file Radiobuttonlist displays as dropdownlist as well as radiobuttonlist on web page I want placeholder instead of names again all the fields And what is the reason behind that 2 times printed fields??? -
How can I debug JWT authentication on Django
I am developing jwt authentication function on Django and I got the HTTP 401 error. I want to know how can I dubug it? I want to know what's going on my code. But I have no idea what are dubug tools in this case. Would you give me some advice please? -
Django annotation and group by time range?
I am using the following query to get a sum per day: orders = OrderM.objects.filter(user=request.user) \ .annotate(day=TruncDay('datetime_added')) \ .values('day') \ .annotate(sum=Sum(F('orderd__good_count'))) \ .order_by('-day') as expected each day changes at 00:00 midnight! I want to change this behaviour so that each day changes at 06:00, meaning that I want the sum to be generated on periods from 06:00 to 06:00. I think that the use of datetime__range = .. will do, but I'm not experienced in django queries. Thanks... -
Django image upload not uploading japanese named image
The error i am getting when uploading japanese named image is : 'ascii' codec can't encode characters in position 45-48: ordinal not in range(128) Images are uploading perfectly when named in english characters. My model: class Tenant_Post(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,null=True) name = models.CharField(max_length=255,null=True) image = models.FileField(upload_to='image/tenant/',null=True) posted_on = models.DateTimeField(auto_now_add=True, auto_now=False) last_modified_on = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return self.name My view: @login_required(login_url='/') def new(request): if request.method == 'POST': print request.POST form = TenantForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() print 'success' return HttpResponseRedirect(reverse('tenant:all')) else: print 'fail' return render(request,'tenant/new.html',{'form':form,}) else: form = TenantForm() return render(request,'tenant/new.html',{'form':form,}) -
Getting Empty Result in Haystack Django Solr
Follow https://django-haystack.readthedocs.io/en/latest/debugging.html Everything is Ok, but got empty results Note: page.object_list is always empty Why ? Thanks in Advance -
django REST filter SerializerMethodField
Refer to official docs. I have to filter by queryset. But my knowledge is limited. Then I decided to use SerializerMethodField The list() method are find. It list all the items. Problem: I want to exclude item with [] out class ProductViewMissingDisplayImageSerializer(ModelControllerSerializer): missing_types = serializers.SerializerMethodField(read_only=True) def get_missing_types(self, obj: ProductView) -> typing.List[str]: return check_image_type(obj) AS is Output: { "product_view_pk": 78, "name": "ATF", "service": 4, "display_mode": "IMAGE ONLY", "missing_types": [ "CONTENT IMAGE", "POPUP IMAGE" ] }, { "product_view_pk": 83, "name": "サスティナ(化学合成油)", "service": 4, "display_mode": "IMAGE ONLY", "missing_types": [] }, Expected Result: { "product_view_pk": 78, "name": "ATF", "service": 4, "display_mode": "IMAGE ONLY", "missing_types": [ "CONTENT IMAGE", "POPUP IMAGE" ] }, How can I do that? -
Display pandas data frame on django - Python
I spent few days searching the Internet for a framework for displaying pandas data frame on Django and I can't find a straight forward answer. can someone please give me some guidance? -
Django Login Required Not Redirecting Properly
So I am trying to add a @login_required decorator on my pages that aren't the login page, but when I try to login and redirect to a different page, it does not redirect. I got to my url, then login, and then it adds the /?next=/redirect_page/. So it goes from www.example.com to www.example.com/?next=/redirect_page/ even though it should see that it is logged in and redirect, not add the next part. Below is my code. home.html: <form method="post" class="form-signin" action="{% url 'index' %}"> {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> <h2 class="form-signin-heading">Please Sign In</h2> {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">Submit</button> {% endbuttons %} </form> home/views.py: from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib.auth import authenticate from .forms import SignInForm def index(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = SignInForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required user = authenticate(username=request.POST.get('username', None), password=request.POST.get('password', None)) if user is not None: return HttpResponseRedirect('/redirect_page/') else: form = SignInForm() # if a GET … -
too many values to unpack (expected 2) when i'm using filter()
I have a project in django 1.8 and I want to extract the date_start field to get a year and then create a range in what year the event occurs. Then pass it all to SelectDateWidget in the form: date_start = forms.DateField(widget=SelectDateWidget(years=range(1980, 2018))) But I recived: too many values to unpack (expected 2) Here is part of my code: context['years'] = models.Booking.objects.filter('date_start') -
Can not import the app from my project
Why my app01 unresolved? In my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01', ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], ... STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) -
Django migrations for a cloned db
I cloned a postgres db and added a new model to one of the apps. Our project contains many apps. Now When I ran migrations, migrate it would fail. So I commented that model out, deleted migrations.py file from folder and ran fake migrations. Than again put that model in and ran migrations, migrate. Things were fine. But now I deleted this model table from db manually and when would run migrations it would show model doesn't exist. Basically I would need to again and again tweak the model, delete, update table. So I searched for migrating from scratch. Did delete some apps from django_migrations table. But it is not working out it shows relations already existing. This is all becoming confusing, --fake, delete, squash what to do? Basically if I drop table django_migrations, delete migrations folder from app. Can't django automatically sync with db and understand what model exist and what don't and figure it out itself. -
how can I run redis-server in travis ci?
sorry about my low level english I practice unit test using django In items/tests.py class NewBookSaleTest(SetUpLogInMixin): def test_client_post_books(self): send_post_data_post = self.client.post( '/booksale/', data = { 'title':'Book_A', } ) new_post = ItemPost.objects.first() self.assertEqual(new_post.title, 'Book_A') In views/booksale.py class BookSale(LoginRequiredMixin, View): login_url = '/login/' def get(self, request): [...] def post(self, request): title = request.POST.get('title') saler = request.user created_bookpost = ItemPost.objects.create( user=saler, title=title, ) # redis + celery task queue auto_indexing = UpdateIndexTask() auto_indexing.delay() return redirect( [...] ) when I run unit test, raise redis connection error redis.exceptions.ConnectionError I know when I running redis-server and celery is error will solve but when I run unit test in Travis CI I can't run redis-server and celery in Travis CI So, I found this link I try insert this code in .travis.yml language: python python: - 3.5.1 addons: postgresql:"9.5.1" install: - pip install -r requirement/development.txt service: - redis-server # # command to run tests script: - pep8 - python wef/manage.py makemigrations users items - python wef/manage.py migrate - python wef/manage.py collectstatic --settings=wef.settings.development --noinput - python wef/manage.py test users items --settings=wef.settings.development but it shows same error so I found next link before_script: - sudo redis-server /etc/redis/redis.conf --port 6379 --requirepass 'secret' but... it show same error... how can … -
Pass argument to __init__ of object model class in iterate queryset
I have a model with overridden __init__ method like this: class MyModel(models.Model): ... def __init__(self, *args, **kwargs): if not kwargs.get('skip', False): do_something() super().__init__(*args, **kwargs) How can I pass skip argument to init , when I iter the queryset: data = [obj for obj in MyModel.objects.all()] -
Sometimes use `param max_length`, sometimes not, in the models.py
I find in the models.py of a project, there sometimes use param max_length, sometimes not: class Category(models.Model): caption = models.CharField(16) # no max_length class Article(models.Model): title = models.CharField(max_length=32) content = models.CharField(max_length=255) # there is max_length So, is there difference between them? Whether the caption = models.CharField(16) equals to caption = models.CharField(max_length=16) ? -
OperationalError: table "django_session" already exists
I have applied all solution but still I got an operational error and also when I run project it gives error like: "You have 1 unapplied mugration(s)....." I had applied all migrations. I tried this solution: 1) delete all files under migrations directory except init.py(successfully) 2) run $python manage.py makemigrations (successfully) 3)run $python manage.py sqlmigrate 001 (Successfully) 4) run $python manage.py migrate (Failed: operational error) Because of 4th failure I got a statememt of migrations while I ran project What should I do?? -
Recommender System : ValueError at / could not convert string to float:
I am trying to build a movie recommender web application using python and django. I am trying to use a command to take the movie's descriptions and create an information retrieval system to allow the user to find movies typing some relevant words. This tf-idf model is then saved in the Django cache together with the initial recommendation systems models (CF item-based and log-likelihood ratio). The command to load data is python manage.py load_data --input=plots.csv --nmaxwords=30000 --umatrixfile=umatrix.csv Terminal Error File "/home/anthra/server_movierecsys/books_recsys_app/management/commands/load_data.py", line 80, in handle matr[0]=newrow ValueError: could not convert string to float: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, plot.csv screenshot The code is as follows: matr = np.empty([1,ndims]) titles = [] cnt=0 for m in xrange(nmovies): moviedata = MovieData() moviedata.title=tot_titles[m] moviedata.description=tot_textplots[m] moviedata.ndim= ndims moviedata.array=json.dumps(vec_tfidf[m].toarray()[0].tolist()) moviedata.save() newrow = moviedata.array if cnt==0: matr[0]=newrow else: matr = np.vstack([matr, newrow]) titles.append(moviedata.title) cnt+=1 -
django request.POST.get different button name
HELLO,I have many buttons like: <button name="A"></button> <button name="B"></button> <button name="C"></button> When I click on a button, I want to get the corresponds name, then use it in my view to compare with some string. request.POST.get how to get the value I need? -
Django textfield stretches the width of an html table? How can I prevent this?
I have a django table that's supposed to display the contents of each field of a model called Resource I wrote it like this, with results being a part of the contexts dictionary and simply containing filtered Resource objects. <table style="width: 70%;"> <tr> <th>Title</th> <th>Author</th> <th>Country</th> <th>Description</th> </tr> {% for resource in results %} <tr> <td><a href="{{ resource.link }}">{{ resource.title }}</a></td> <td>{{ resource.author }}</td> <td>{{ resource.country }}</td> <td>{{ resource.description }}</td> </tr> {% endfor %} The basic html table that created currently gets to dimensions of around 1500 x 3200. Pretty big, but that's not because my monitor is big or something like that. As a matter of fact, even if I had the css style set as width: 70% attribute or anything of that sort, the dimensions of the table do not change. If I get rid of the following line, <td>{{ resource.description }}</td> which is supposed to display the Resource model's textfield known as "description", however, then then I can actually customize the width of the table and prevent it from being so long. I need to be able to shorten the width of the table, and particularly this field. What can be done? -
Django Datatables Views doesn't display datatables, only json
I'm pretty new to python, django and javascript. It was a breakthrough to get anything at all to display on my localhost site, but now I'm trying to get it to display as a datatable and it is only populating as raw json data I think. I'm guessing it is probably something in the template that is causing this, but I'm pretty novice so would appreciate any help. Models.py from django.db import models class pitcher(models.Model): id = models.IntegerField(primary_key=True) player_name = models.CharField('pitcher name', max_length=255, default='null') pitch_type = models.CharField(max_length=255, default='null') game_date = models.DateField(null=True, blank=True) release_speed = models.FloatField() pfx_x = models.FloatField() pfx_z = models.FloatField() spin_rate = models.FloatField() estimated_ba_using_speedangle = models.FloatField() estimated_woba_using_speedangle = models.FloatField() babip_value = models.FloatField() Usage = models.FloatField() urls.py from django.conf.urls import url from analyzer import views from analyzer.views import pitcherlist import json urlpatterns = [ url(r'^$', pitcherlist.as_view(), name='pitcherlist_json'), ] views.py from django.shortcuts import render from .models import pitcher from django_datatables_view.base_datatable_view import BaseDatatableView import json from django.http.response import HttpResponse class pitcherlist(BaseDatatableView): model = pitcher columns = ['player_name', 'game_date','pitch_type', 'pfx_x'] max_display_length = 500 template <!DOCTYPE html> <html> <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css"/> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script> <head> </head> <body> <div class="container"> <div class="row"> <div class="col-sm-12 col-md-12"> <div class="well"> <table id="pitcherlist" class="display responsive" width="100%"> <thead> … -
django-social-auth : custom response during pipeline execution
I'm using social-auth-app-django for Google authentication process. I created a custom pipeline and I want to return a 403 Forbidden response under some certain conditions during the pipeline execution or somehow. def check_condition_pipeline(strategy, backend, details, response, *args, **kwargs): email = details['email'] if email == 'check_email@domail.com': return {'is_new': False} else: # raise '403 Forbidden' # show HTTPResponse as {"response": "Not Autherised"} I tried redirect() method, but didn't get what I expected :( -
How to make a model field as hyperlink in django models
class Trip(models.Model): trip_number = models.CharField( _("Trip Number"), max_length=128, db_index=True, unique=True, blank=True) what i am looking is to make this trip_number as hyperlink.