Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-VueJs List component views all titles as "List" and no images are viewed
I try to create an application using Django RestAPI and Vuejs. I can get my articles, I have created a component for templating my article view. But all the titles are viewed as "List". I cant also bind my images. And the other problem is articles are not aligned they are listed in vertical line. This how I use my template: <div v-for="article in articles" > <articlelist title="article.title" content="article.content" image ="article.image" :key="article.id"></articlelist> </div> My component is var articlelist = { template: ` <div class="col col-xl-4 col-lg-4 col-md-6 col-sm-6 col-12" > <div class="ui-block"> <!-- Post --> <article class="hentry blog-post"> <div class="post-thumb"> <img v-bind:src="image" alt="photo"> </div> <div class="post-content"> <a href="#" class="post-category bg-blue-light">THE COMMUNITY</a> <a href="#" class="h4 post-title">{{title}}</a> <p>{{content}}</p> <div class="author-date"> by <a class="h6 post__author-name fn" href="#">{{author}}</a> <div class="post__date"> <time class="published" datetime="article.created_at"> - 7 hours ago </time> </div> </div> <div class="post-additional-info inline-items"> <div class="friends-harmonic-wrap"> <ul class="friends-harmonic"> <li> <a href="#"> <img src="img/icon-chat27.png" alt="icon"> </a> </li> <li> <a href="#"> <img src="img/icon-chat2.png" alt="icon"> </a> </li> </ul> <div class="names-people-likes"> 26 </div> </div> <div class="comments-shared"> <a href="#" class="post-add-icon inline-items"> <svg class="olymp-speech-balloon-icon"> <use xlink:href="svg-icons/sprites/icons.svg#olymp-speech-balloon-icon"></use> </svg> <span>0</span> </a> </div> </div> </div> </article> <!-- ... end Post --> </div> </div> `, props: ['title', 'content', 'image', 'author'] }; And I get my … -
Heroku django overwriting a temp file
I'm writing a django application, where, a user records a message, the message is converted with FFMPEG and uploaded to a FS,now, FFMPEG doesn't allow file overwrite, so i'm creating a new file and than replacing the old one before inserting it my filesystem. so basically: The file is recorded in the front-end -> sent to the backend and stored as a tempfile (automatically by django) -> the files gets converted -> the file is uploaded to the fs. (the file is converted from around 2mb to 200kb, which is an indicator to if the file was converted) now, to replace the original file, I use shutil.move(), and when i run it on my system, and then I look in my fs, the file sure is only 200kb, but when i push the same code to Heroku, i do the same operation, when look in the fs I see that the new file is still 2mb, also, I know the conversion was done from the server logs, whitch means that the file replacing failed but only on Heroku, am i missing something? -
Setting up jQuery in Django 2
I am new to Django . I followed a guide to setup the jQuery on my project. In my static folder i have file name jQuery. And in my base html i am using it like this: <script src="{% static 'js/jquery-3.3.1.min.js' %} "></script> I have another file called main.js in my base.html file . which is also pointing towards the js file in my static folder just like the jQuery file. In main.js file i have put my jQuery code which is to fadeout the message after certain time. setTimeout(function() { $("#message").fadeOut("slow"); }, 3000); But it doesn't seem to work. I searched online but every one mentioned the same procedure. To download the static jQuery file and place it in static folder inside main app and then run collectstatic. I have tried using some other jQuery methods but they don't seem to be working either. I tried js code inside script tags to see if jQuery is loaded. It shows the correct message. But what i don't understand is why it's not working. Am i missing something obvious here? Thanks. -
Add extra fields to User Profile view in Django REST Framework
I'm using Django 2.x and Django REST Framework. By default, DRF provides an endpoint for Profile Details which returns details of authenticated user from the User model. The default view provides fields fields = ('pk', 'username', 'email', 'first_name', 'last_name') and the endpoint is /api/user/ I want to add more fields to the serializer as I'm using a custom User model and have more fields added to it. Do I need to create a Custom view and redefine the serializer class or I can extend the default provided view and serializer to add extra fields? -
Django test client does not provide the right authentication headers
When sending a request to the development server, I can include a header as follows: Authorization: Token efc7fa291f4e320ff4a31cf9a11d6de3a366937cd1ec24e0a7ab68dafa38430f\r\n Internally Django sees an HTTP_AUTHORIZATION header, which I am not sure where is generated. But when using the Django test client for unit testing: from django.test import Client c = Client() response = c.get('/api/auth/user/', **{'Authorization': 'Token ' + token}) Django can not authorize the request. If instead I do the following: response = c.get('/api/auth/user/', **{'HTTP_AUTHORIZATION': 'Token ' + token}) It works. I would like to understand what is going on. Who is responsible of performing the mapping Authorization -> HTTP_AUTHORIZATION? Relevant for this question: I am using Django 2.1.5, djangorestframework = "==3.9.0" and djangorestframework = "==3.9.0" -
Calculations using percentages decimal or readable
Simple question (and apologies if this is too opinion based): How should I store percentages? When writing a program which includes a large number of analytical calculations, or financial calculations involving percents (return rates, APRs, profit margins etc), which of the three options below are best practice, in terms of performance, readability, good code practice etc. Store percentages as floats in decimal form: ie 20% = 0.20, and write a filter to transform this in the UI. (In django this would be a templatetag, which would need to be applied everytime a percentage was dislayed). Store percentages as whole numbers and divide by 100 whenever calculations need to be done in the backend, ie 20.13% is stored as 20.13 and used like percent/100 * myNumber. Create (or use a library) a datatype for Percent, which can do both, such as having an attribute 'Percent.value' with a property decorated attribute for 'Percent.display' which multiplies by 100 and rounds. As far as I see, 1 is the most intuitive, but doesn't seem like best practice for encapsulation, and could lead to issues with errors displaying odd values, debugging and etc. 2 seems to be insanely annoying for developers, and could lead to … -
Request changes/additions to data in another app
To make a long story short, I am very grateful for hints on how I can accomplish the following. I have an app A that I don't want to change. I have an app B that needs to select data from A or to request data to be added/changed if necessary. Think of B as an app to suggest data that should end in A only after review/approval. By itself, B is pretty useless. Furthermore, a significant amount of what B's users will enter needs to be rejected. That's why I want A to be protected so to say. # in app A class Some_A_Model(models.Model): #e.g., think artist some_value = models.TextField() # in app B class MyCustomField(models.ForeignKey): ... class Some_B_Model(models.Model): # e.g., think personal preference best_A = MyCustomField('Some_A_Model') worst_A = MyCustomField('Some_A_Model') how_many_times_I_like_the one_better_than_the_other = models.FloatField() class Mediator(models.Model): # already exists: generic foreign key content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE ) object_id = models.PositiveIntegerField() content_object = GenericForeignKey( 'content_type', 'object_id' ) #does not yet exist or needs to be changed: add_or_change = PickledObjectField() Django should create a form for Some_B_Model where I can select instances of Some_A_Model for best_A and worst_A, respectively; if, however, my intended best_A is not yet in A's database, … -
If then else Django forloop logic question
I have a homepage which currently runs a forloop to show all users. {% for user in users %} On that same page, there is a form to filter by radius (km) to see users close to you. Currently, after you submit a radius to filter the users, nothing is returned because there is no {% for user in location %} forloop yet. I know I need some {% if xxx %} {% else %} {% endif %} statements but I'm unsure how to write them. Essentially, if no filter is selected / radius is submitted I want to return all users (like it does right now). But if a radius is submitted or a filter is applied, I want the page to return the results of the queryset / multiple querysets. Many thanks and any suggestions on cleaning up my code are always appreciated as I am a beginner. views.py class ConnectView(View): template_name = 'connect/home.html' def get(self, request, *args, **kwargs): context = { 'users': User.objects.exclude(username=request.user), 'friends': Friend.objects.filter(current_user=request.user), } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): location = Location(latitude=request.POST['latitude'], longitude=request.POST['longitude'], user = request.user) location.save() return JsonResponse({'message': 'success'}) def location(request): if request.POST: radius_km = request.POST.get('radius', 0) queryset = User.objects.annotate( … -
Updating model data to match list
Backround: I am pulling data from an API and creating a list like the one below. Now this data set will be 50 entries each time, and changing just about every time I'm saving data into my model. So below i created a condensed version of what is going on in my Django project. I insert my data into my model by using a list like so: list = [(1, "open", "hello"), (2, "closed", "hey"), (3, "in progress", "never"), (4, "open", "free")] and then saving these values into model 'Bug' like this for item in list: b = Bug(key=item[0], status=item[1], description=item[2]) b.save() Now say the list changes to this list = [(3, "closed", "never"), (4, "closed", "free"), (5, "open", "never"), (6, "open", "great")] (note the entry with "3" as the key has changed from "in progress" to "closed" and the item with "4" as the key has also changed to "close". This also adds entries with a key of "5" and "6") With the existing saved model data from the first list, how can i update the saved model data to reflect the changes of the 2nd list? as well as add entries. -
Autofocus on email field after return render request in views.py
I'm working with signup form it is working fine, but i want to set focus on email field after the message.error appear. I am new to django and just starting programming again. from django.shortcuts import render, redirect from django.contrib import messages, auth from django.contrib.auth.models import User from django.contrib.auth import logout from django.http import HttpResponse, HttpResponseRedirect def signup(request): if request.method == 'POST': # Get Form Values first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] username = email password = request.POST['password'] password2 = request.POST['password2'] context = { 'first_name' : first_name, 'last_name' : last_name } # Check if passwords match if password == password2: #Check username if User.objects.filter(username=username).exists(): messages.error(request, 'Email is taken and used') return render(request, 'accounts/signup.html', context) else: #Looks good user = User.objects.create_user(username=username, email=email, password=password,first_name=first_name,last_name=last_name) user.save() messages.success(request, 'You are now registered and can log in') return HttpResponseRedirect('/#signin') else: messages.error(request, 'Password do not match') return render(request, 'accounts/signup.html', context) else: return render(request, 'accounts/signup.html') I just wanted to set focus on email field is there a django way to do that -
Running migrations: No migrations to apply
I want to test django-embed-video from their official git reposiotry Django-embed-video example project Here is their instructions.Django example project docs Example project For easy start with using django-embed-video, you can take a look at example project. It is located in example_project directory in root of repository. Running example project Install requirements: pip install -r requirements.txt Create database: python manage.py migrate --run-syncdb --noinput Or, for older versions of Django: python manage.py syncdb --noinput Run testing server: python manage.py runserver Take a look at http://localhost:8000 . You can log in to administration with username admin and password admin. I followed all their instructions when I run. python manage.py migrate --run-syncdb --noinput I get the following Operations to perform: Synchronize unmigrated apps: embed_video, example_project, messages, posts Apply all migrations: admin, auth, contenttypes, sessions, sites Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: No migrations to apply. When I run python manage.py runserver 8080 I get the following Performing system checks... System check identified no issues (0 silenced). February 13, 2019 - 15:52:08 Django version 1.11.20, using settings 'example_project.settings' Starting development server at http://127.0.0.1:8080/ Quit the server with CTRL-BREAK. When I go to http://127.0.0.1:8080/ I see the following What am I … -
Cant render an image from Django API in VueJs
How do I render an image from Django RestAPI to Vuejs Frontend. I can get all the model elements in VueJS but image rendering causes => invalid expression: Unexpected token { in ${article.image} Raw expression: v-bind:src="${article.image}" (found in <Root>) My template is <article class="hentry blog-post" v-for="article in articles"> <div class="post-thumb"> <img v-bind:src="${article.image}" alt=""> </div> <div class="post-content"> <a href="#" class="post-category bg-blue-light">THE COMMUNITY</a> <a href="#" class="h4 post-title">${article.title} </a> <p>${article.content}</p> <div class="author-date"> by <a class="h6 post__author-name fn" href="#">${article.author}</a> <div class="post__date"> <time class="published" datetime="2017-03-24T18:18"> - 7 hours ago </time> </div> </div> <div class="post-additional-info inline-items"> <ul class="friends-harmonic"> <li> <a href="#"> <img src="{% static 'img/icon-chat27.png' %}" alt="icon"> </a> </li> <li> <a href="#"> <img src="{% static 'img/icon-chat2.png' %}" alt="icon"> </a> </li> </ul> <div class="names-people-likes"> 26 </div> <div class="comments-shared"> <a href="#" class="post-add-icon inline-items"> <svg class="olymp-speech-balloon-icon"><use xlink:href="/static/svg-icons/sprites/icons.svg#olymp-speech-balloon-icon"></use></svg> <span>0</span> </a> </div> </div> </div> </article> Thanks -
Django Rest Models ImproperlyConfigured:
I'm trying to use Django ORM where it queries an API rather than a database. I found the library Django Rest Models which does this in conjunction with the library dynamic-rest. My model is called Client, and I'm getting the following error. ImproperlyConfigured: the response does not contains the result for client. maybe the resource name does not match the one on the api. please check if Client.APIMeta.resource_name_plural is ok This is my model on the client class Client(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) agent = models.ForeignKey(Agent, db_column='agent') ..... class APIMeta: resource_path = 'clients' resource_name = 'client' resource_name_plural = 'clients' pass This is my code on the API class ClientSerializer(DynamicModelSerializer): agent = DynamicRelationField('AgentSerializer') class Meta: fields = '__all__' model = Client name = 'client' class AgentSerializer(DynamicModelSerializer): client = DynamicRelationField('ClientSerializer', many=True) class Meta: fields = '__all__' model = Agent -
Multiple Users access Same Token
Can i implement one client id and one client secret for multiple users using Oauth2. Can any one Explain Oath2 Token Authentication because i am not getting a proper tutorial on it. -
How to Create A subscription button in Django
I'm new to web development and Python programming. i want to create a button where users can subscribe/unsubscribed to a subchannel (much like a forum category) in a forum. what i really want is for a user to be capable of subscribing and unsubscribe by clicking the button ( of the subchannel) views.py file class SubChannelSubscriptionView(ListView): template_name = 'subscription.html' model = Topic def get_queryset(self): return SubChannelSubscription.objects.filter(user=self.request.user) def get_context_data(self, **kwargs): context = super(SubChannelSubscriptionView, self).get_context_data(**kwargs) context['SubChannel'] = SubChannel.objects.all() context['top'] = Topic.objects.filter(category__subchannel_subs__user=self.request.user) return context def subd(self, request): subchannel = get_object_or_404(SubChannel, pk=self.kwargs['pk']) is_subd = False if subchannel.subd.filter(pk=request.user).exists(): subchannel.subd.remove(request.user) is_subd = False else: subchannel.is_subd.add(request.user) is_subd = True return reverse('index') models.py file class SubChannel(models.Model): title = models.CharField(max_length=150, unique=True, null=True) description = models.CharField(max_length=150, null=True) channel = models.ForeignKey(Channel, on_delete=models.CASCADE, related_name='channel') subd = models.ManyToManyField(User, related_name='subd' ) subscription.html file form action="{% url 'index' %}" method="post"> {% csrf_token %} {% if is_subd %} {% for sb in SubChannel %} <button type="submit" value="" > subd{{ sb }} </button> {% endfor %} {% else %} {% for sb in SubChannel %} <button type="submit" value="" >not sub {{ sb }} </button> {% endfor %} {% endif %} -
Django login method doesn't put user in session
I am creating an api for news stories using django. I need a login method so I have created my own handler: def HandleLogin(request): if(request.method == 'POST'): un = request.POST.get('username') pw = request.POST.get('password') # data = 'user name = ' + un + ', password = ' + pw user = authenticate(request, username = un, password = pw) if user is not None: if user.is_active: login(request,user ) if(user.is_authenticated): # print('Welcome ' + user.username ) http_login_succ = HttpResponse("Welcome "+ user.username) http_login_succ['Content-type'] = 'text/plain' http_login_succ.status_code = 200 http_login_succ.reason_phrase = 'OK' return http_login_succ else: return HttpResponse ('disabled account') else: return HttpResponse('invalid login') After that I want only logged in users to be able to access the point in the website where you post news stories: def PostStory(request): if request.user.is_authenticated: return HttpResponse("Logged in") #Code when logged in else: return HttpResponse("Not Logged in") I then log in successfully getting the 'Welcome' username message but then when accessing poststory it never recognizes the logged in user. -
Try-Catch in Django doesn't work in python3.6
I've been studying "Test-Driven Development with Python: Obey the Testing Goat: Using Django, Selenium, and JavaScript 2nd Edition" https://www.amazon.com/dp/1491958707 I had challenged to rewrite the tutorial's code, yet couldn't. My reason Try-Catch in Django doesn't work is bellow; Django.test.TestCase module has no functions that operate normally Try-Catch. I type the command, when I would like to run test.py. $ python manage.py test Here are my codes. app(directory name)/tests.py from django.urls import resolve from django.test import TestCase from django.http import HttpRequest from app(directory name).views import home_page class HomePageTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual(found.func, home_page) def test_home_page_returns_correct_html(self): request = HttpRequest() response = home_page(request) html = response.content.decode('utf8') try: #self.assertIn('<title>To-Do lists</title>', html) self.assertEqual('<title>To-Do lists</title>', html) except AssertionError: self.assertTrue( html.startswith('<html>')) self.assertTrue(html.endswith('</html>')) else: #pass self.fail('Finish the test!') app(directory name)/views.py from django.shortcuts import render from django.http import HttpResponse #home_page = None def home_page(request): #pass #return HttpResponse('<html><title>To-Do lists</title></html>') return HttpResponse('<html><title>Hello World!</title></html>') Infomation related to my development $ python --version python 3.6.5 $ django-admin version 1.11.8 $ cat /etc/os-release NAME="Ubuntu" VERSION="16.04.5 LTS (Xenial Xerus)" .... $ pip freeze Django==1.11.8 pkg-resources==0.0.0 pytz==2018.9 selenium==3.141.0 urllib3==1.24 I would be glad to you to give me answer, if you have time. -
Django export function and Celery task
I would like to use Celery in order to run asynchronously my task and I'm getting some troubles with that. I would like to create a data file through export method. Context : User can export search result into a .xlsx file. However there are 2 cases : Search contains less than 70.000 rows. In this way, user can directly download the generated output file with HttpResponse. Search contains more than 70.000 rows. In this case, the file is written in the media folder thanks to a Celery task. By this way, even if the file is available few minutes after the request, user can navigate through the application. He will receive an email containing the link to download his generated file. I'm working on this second part and I'm getting issues to set the Celery task. My code : This is the button used to execute the Celery task in my HTML template : {% if item_count > 70000 %} {% if search_info_str %} <a title="Print" href="{% url print_link model='finalproduct' search_info=search_info_str %}" class="button btn btn-default print_items"><span class="glyphicon glyphicon-print"></span></a> <a title="Export to Excel" name="export" class="button btn btn-default" href="{% url 'ocabr:cron_export' model=model search_info=search_info_str %}"><span class="glyphicon glyphicon-export"></span></a> {% else %} <a title="Print" … -
Authentication Against Company Django Rest OAuth2
I have one Company Model and User Model. I want to create client_id and client_secret against company name. And when user accessing API Username and Password will be sended along with Companies client_id and client_secret. When user is authenticated then api will be visible. Which Grant Type can i use, How can i differentiate users who is accessing api. -
Django 2.1 create method to create nested fields (foreignkey relation). Using Django's Rest Framework
Which method should I use in jango 2.1 for the create method to add new objects that supports also the creation of nested fields (ForeignKey relation). I always get the Error Message: AssertionError at /client/create/ The .create() method does not support writable nested fields by default. My Model class ClientCompany(models.Model): client = models.ForeignKey(Company, on_delete=models.PROTECT) contact_person = models.ForeignKey(User, on_delete=models.PROTECT) status = models.CharField(max_length=15, choices=STATUS, default='Aktiv') def __str__(self): return f"{self.client} {self.contact_person} {self.status}" My Serializer class ClientCompanySerializer(serializers.ModelSerializer): client = CompanySerializer(many=False, read_only=False) contact_person = ClientUserSerializer(many=False, read_only=True) class Meta: model = ClientCompany fields = '__all__' Is there a way to create the related 'contact_person' within the 'ClientCompanySerializer' or should I use a different approach. -
How to sum two model fields together in Django
I am creating an eCommerce website and I am busy with the shopping cart at the moment. Currently I display product, quantity and order date. I would like to also display the order total for each order. Currently my models look like this: models.py class Store(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=250) store_owner = models.ForeignKey(UserAccount, on_delete=models.CASCADE) def __str__(self): return self.name class Product(models.Model): product_name = models.CharField(max_length=100) price = models.IntegerField(null=True, blank=True) description = models.TextField(max_length=250) store = models.ForeignKey(Store, on_delete=models.CASCADE) def __str__(self): return self.product_name class Cart(models.Model): user = models.ForeignKey(UserAccount, on_delete=models.CASCADE) order_total = models.IntegerField(null=True, blank=True) checked_out = models.BooleanField(default=False) def __str__(self): return str(self.user) class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(null=True, blank=True) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) order_date = models.DateTimeField(auto_now=True) order_total = models.IntegerField(null=True, blank=True) def __str__(self): return "{} order".format(self.product) How do I add quantity and price together and assign it to order_total? I also can't figure out how to assign it dynamically because each user would have a different total. I have looked at Django: Calculate the Sum of the column values through query but I can't figure out how to apply it to my models. Any suggestions? -
Client-Crendentials in Django Rest Oauth2
I am using Authorization Grant Type as Client-Crendential. But when i am accessing it using `access_token http://localhost:8000/api/jobs/list/access_token=yTpq4qbjnp4gTI7Ur7HRiYGIjGteMn` it is giving error/message as { "detail": "You do not have permission to perform this action." } Settings.py OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework.authentication.SessionAuthentication', # To keep the Browsable API ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } I am not able to see data. -
Share Large Pandas Dataframe between requests
Summary I am developping a django app for data visualization, the user can load a csv and generate plots. Current architecture The user loads his csv by using a form and the csv is stored as json in the session (requests.session). For each http query, the json dataframe is retrieved from the session and converted to a Pandas Dataframe object. Problem This solution works well when the dataframe is small but with large datasets this process becomes too longer (many seconds) The conversion from json to dataframe object takes a lot of time. Note that there is no login system, so the application allows user to load a csv and export a project but the application must not permanently save anything Does anyone have any idea of an architecture that could work? I thought of using a database where the dataset would be saved for the time of use and deleted from the database once the user closes the project. Is this a good solution? -
Image Upload Fails with MultiValueDictKeyError :DJANGO
I am calling Image upload Api(Django rest api) from my view in seperate django project my View if request.method == 'POST' and request.FILES['file']: try: resp = requests.post( "http://19.******/BankImage_API", files = {"file" :request.FILES['file']}, headers={"content-type": "multipart/form-data", "Authorization": "Token 71117971*************" }, verify=False) Api class Bankimageapi(APIView): def post(self, request): if request.method == 'POST' and request.FILES['file']: try: ........ when I tried to Upload Image. i get error in api where FILES <MultiValueDict: {}>. django.utils.datastructures.MultiValueDictKeyError: 'file' Please guide me solve this problem . -
django rest framework x
class CarrierExtraInfo(models.Model): CustomUserID = models.OneToOneField(User,on_delete=models.CASCADE,null=True,blank=True) somevalue = models.CharField(max_length=100,null=True,blank=True) is_active = models.BooleanField(default=True) created_DT = models.DateTimeField(auto_now_add=True) updated_DT = models.DateTimeField(auto_now=True)`enter code here`