Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Spotify API authorisation
I have developed a simple Django app, using Spotify API and Spotipy Authorisation (authorisation flow). This runs a localhost server where I click a simple button which creates a playlist in Spotify. My issue however is in setting this up for an alternative user to login via their credentials and gain authorisation. Atm, I have set this app up using a hardcoded cid and client secret within the views.py module (in the backend). This uses the following code to gain auth. token = util.prompt_for_user_token(username, scope, client_id= cid, client_secret= secret, redirect_uri=r_uri) My index.html file then links a button to this script so that when clicked, the playlist is created. I expect this index.html needs to be updated to allow the user to login to their own spotify account and to authorise their token. However I am unsure on how to update this or if I am on the right track. Alternatively, I think I may need to restart the project using java to gain authorisation for another user or using Implicit Grant Auth method, if spotipy authorisation cannot be used. -
how can i resize bootstraps cards for a website using django?
I just started in the programming world and i'm currently trying to learn python and some django, so i apologized in advanced if this is a dumb question, now back to the point, i'm trying to add some cards from bootstrap to a website to display images of the products with their prices and the option to add then to the cart but since the image in this card are being retrieved from another website, when i tried to load my page the images are too big and the cards don't resize automatically with the browser window so it shows one on top of another. -
'Cannot add or update a child row: a foreign key constraint fails' While creating a new django model object
I have two models 'inventory_barcodes' and 'transfer_inventory' like: Transfered barcodes: class TranferedBarcode(models.Model): id = models.IntegerField(primary_key=True) barcodes = models.CharField(max_length=45, blank=True, null=True) transfer_lot_id = models.ForeignKey('InventoryTransfer', models.DO_NOTHING, db_column='transfer_lot_id') class Meta: managed = False db_table = 'tranfered_barcode' and Inventory Transfer: class InventoryTransfer(models.Model): id = models.IntegerField(primary_key=True) barcodes = models.TextField() to_warehouse = models.CharField(max_length=255) from_warehouse = models.CharField(max_length=255) total_count = models.IntegerField() approval_flag = models.IntegerField(default=0) current_status = models.CharField(max_length=50, blank=True, null=True) error_message = models.CharField(max_length=255, blank=True, null=True) created_by = models.CharField(max_length=50, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) transfer_lot_id = models.IntegerField() class Meta: managed = False db_table = 'transfer_inventory' I'm creating two objects for each model in a view for eg: n = random.randint(1,10000000) InventoryTransfer.objects.create(barcodes=barcodes, to_warehouse=to_warehouse, total_count=barcode_count, created_by=request.user.username, from_warehouse=current_warehouse, current_status="Pending", transfer_lot_id=n) transfer_obj = InventoryTransfer.objects.get(id=36) TranferedBarcode.objects.create(barcodes='SPBA121212',transfer_lot_id=transfer_obj) While doing this I'm getting error as "Cannot add or update a child row: a foreign key constraint fails' While creating a new django model object." I'm stuck here, so any help would be needful. Thanks in advance. -
How to Submit a category form in Django?
I am trying to submit a category form in Django,but it's not saving data in my Database table and it's redirecting me on create category page. I have already created a forms.py file, but that's not working properly, I am working with creating my custom HTML form, Please check my code and let me know where i am Mistaking, and how i can submit this form data in Database table. Here are my Urls.py file... urlpatterns = [ url(r'^category/create/$',views.add_cat, name="catadd"), ] Here are my models.py file code... class Category(models.Model): catType=models.IntegerField(default=None) cat_name=models.CharField(max_length=225) cat_slug=models.SlugField(max_length=225, unique=True) meta_title=models.CharField(max_length=225) meta_desc=models.CharField(max_length=285) meta_keyword=models.CharField(max_length=285) status=models.BooleanField() linkable=models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.cat_name Here are my forms.py file... from django import forms from .models import Category class CategoryForm(forms.ModelForm): class Meta: model=Category fields=('catType','cat_name','cat_slug','meta_title','meta_desc','meta_keyword','status','linkable') Here are my views.py files.. def add_cat(request): if request.method=='POST': form = CategoryForm(request.POST) if form.is_valid(): cate = form.save(commit=False) cate.save() return redirect('dashboard/category') else: form=CategoryForm() return render(request, 'dashboard/category/createcat.html', {'form': form}) here are my createcat.html file.. <form class="form-horizontal m-bottom-30 catForm" id="wizard-arrow" method="POST" action="{% url 'dashboard:catadd' %}" novalidate="novalidate"> {% csrf_token %} <ul class="list-steps"> <li class="col-sm-4 step-item-arrow active"> <a href="#arrow-one" data-toggle="tab"> <i class="fa fa-lock bg-primary"></i> <span>Category Name Section</span> </a> </li> <li class="col-sm-4 step-item-arrow"> <a href="#arrow-two" data-toggle="tab"> <i class="fa fa-gear … -
Change form_field.required inside UpdateView.form_valid
I have a field with blank=True. Inside my UpdateView form_valid method i have an if condition. Is it possible to make it so, if if cond == False, the form will act as if the field is required and throw a prompt to fill-in the field, and not a sever error. -
Different redirect on form submit in a Django view
Is it possible to redirect to a page or another when sending a request.POST in a Django view, depending on which button has been used? Example: <form id="myForm" action='.'> <submit button1> <submit button2> </form> and then in my view: if request.method == "POST": if form_.is_valid() and button1: form.save() return redirect('page1') if form_.is_valid() and button2: form.save() return redirect('page2') -
Showing list of items including item details on same page in Django
In a Django v3.x app I would like to display a list of uploaded file names (e.g. images) in the left hand side of the screen. When a user clicks on one of those, I'd like to display the actual file/image on the right hand side of the screen. I am still new to Django and have used both ListView and DetailView separately, but not in such a combination. I'm not sure how this can be achieved. Using a little Bootstrap magic, I can create a split screen easily. Hence, my template would look somehow like this: <div class="row"> <div class="col-md-5 left"> {% for image in images %} <div class="card"> <h4>{{ image.url }}</h4> <a href="{{ image.url }}">View</a> </div> {% endfor %} </div> <div class="col-md-5 right"> {# TODO: When the user clicks on the View url above, then I'd like to load the actual image here on the right hand side of the screen inside this div-tag. #} </div> </div> Question 1: How can I achieve loading a selected image from a list? Can I still use ListView and DetailView, or do I need to write my own View logic? Question 2: Ideally, I'd like to NOT re-send the whole page … -
How to create model allowing infinite submodels in django?
Im creating a site where you can write down your goals, you should be able to split every goal into subgoals if chosen, and allow those subgoals to be split into subgoals infinitely. This code below shows what i came up with first for the models, the first model is for creating a goal, the second model can either either be a subgoal of the goal or a subgoal of the subgoal. But it seems like a really bad way to go around this problem. Django semi-newbie BTW... from django.db import models from django.contrib.auth.models import User class Goal(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) title = models.CharField(max_length=70, null=True) content = models.TextField(blank=True) slug = models.SlugField(max_length=50, editable=False) date_created = models.DateTimeField(auto_now_add=True, null=True) class Meta: unique_together = ['user', 'title'] def __str__(self): return self.user.username + " - " + self.title def save(self, *args, **kwargs): self.slug = self.title.replace(' ', '-').lower() super(Goal, self).save(*args, **kwargs) class SubGoal(models.Model): goal = models.ForeignKey( Goal, on_delete=models.CASCADE, null=True, blank=True) parent = models.ForeignKey( "SubGoal", on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=70) content = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): try: return self.goal.title + " - " + self.title except: return self.parent.title + " - " + self.title -
How to use p5.sound.js library in Django?
I have a problem with p5.sound.js in Django. When I create AudioIn() object in my javascript file I get this error in web browser: "TypeError: arraySequence[0] is undefined2 f1a53862-ad3a-488b-a58a-c9b8c40fa664:75:28 push blob:http://127.0.0.1:8000/f1a53862-ad3a-488b-a58a-c9b8c40fa664:75 process blob:http://127.0.0.1:8000/f1a53862-ad3a-488b-a58a-c9b8c40fa664:170" The only thing I do in my js code is "mic = new p5.AudioIn();" - in this moment the error appears. I have tried to use the library both downloaded and from cdnjs.cloudflare.com. -
relation between models (tables) in dajngo
how to make such relations class Laptop(models.Model): name = models.CharField(max_length=20) class SerialNumber(models.Model): serial_number = models.CharField(max_length=13,unique=True) each single computer has a unique serial number , for example we have 5 MacBook Air (13-inch, 8GB RAM, 256GB SSD Storage) - Space Gray and also we will have 5 unique serial number for MacBook Air as a barcode, i add when quantity selected class Computers(models.Model): serial_number = models.ForeignKey(SerialNumber,on_delete=models.CASCADE) name = models.ForeignKey(Laptop,on_delete=models.CASCADE) quantity = models.IntegerField() when i sell more than one MacBook Air , use their barcodes (serial number) during selling , and sometimes more than one laptop model in one form class LaptopSellingForm(models.Model): name = models.CharField(max_length=20) items = models.ManyToManyField(Computers,through='Laptops') date = models.DateTimeField(auto_now_add=True) i need a connection that allow me after selected Computer Model , then allow me to access serial number , then if quantity=3 then i will choice 3 serial number class LaptopsSelling(models.Model): computer = models.ForeignKey(Computers,on_delete=models.CASCADE) quantity = models.IntegerField() should i add serial_number field to LaptopsSelling as a foreignKey then control the number of serial_number fields with InlineFormset i much appreciate your helps -
Conditional formatting django css
I pretty new to Python and Django. My first Project is a MS Teams Status Call Monitor. Its working so far. But I asked myself if its possible to format the Table different when having a change in my Status. Available = Green Away = Yellow Busy = Red How can I do that with Django / CSS? {% extends "tutorial/layout.html" %} {% block content %} <h1>Teams</h1> <table class="table"> <thead> <tr> <th scope="col">Activity</th> <th scope="col">Availability</th> </tr> </thead> <tbody> <tr> <td>{{ status.status }}</td> <td>{{ status.availability }}</td> </tr> </tbody> </table> {% endblock %} Thanks :) -
I cant update a data object in python. I have a model called choice with 2 object one of the is vote i need to update its valu
enter image description here moodel enter image description here Views.py vote views. -
how to do real time video/audio streaming in django
i want to stream the video and audio (and some real time data which i will get from precessing every fram) from surveillance camera into a django website ... i found this code that help me send frames to the client ''' from django.shortcuts import render from django.http import HttpResponse, StreamingHttpResponse import cv2 import time from django.views.decorators import gzip class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture('./streaming/video.mp4') def __del__(self): self.video.release() def get_frame(self): ret, image = self.video.read() ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def index(request): try: return StreamingHttpResponse(gen(VideoCamera()), content_type="multipart/x-mixed-replace;boundary=frame") except HttpResponseServerError as e: print("aborted") but i dont knoow hhow to handle the audio and data and the synchronization . i want to know what technology i have to use and if there any tutorial or ideas about it. i really don't know what to read and how to start (i'm using django). -
Django Migration, Getting User by Username: You can't execute queries until the end of the 'atomic' block
I'm running a data migration that parses a python dictionary and creates objects in a database for every object in the dictionary with their respective fields. The issue is that one of the fields is a user, and the other is a foreign key. When I try and get their objects, I'm met with django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. I know I can probably put with transaction.atomic() somewhere, and I've looked at similar questions on StackOverflow but I can't seem to figure it out. Here's my migration: def upload_change_data(apps, schema_editor): # Import all required apps Change = apps.get_model('changecontrol', 'Change') Server = apps.get_model('changecontrol', 'Server') User = apps.get_model('auth', 'User') # Iterate over every entry in dictionary and add a new change object # to a list of all changes changes = [] for page in initial_data: for entry in page: # Try and find the user that created this object, otherwise # skip the object try: user = User.objects.get(username=page[entry]['admin']) except User.DoesNotExist: continue # Get the server that this change was for computer = Server.objects.get(name=page[entry]['computer']) # Append the change object to the list of changes changes.append( Change(time=page[entry]['time'], server=computer, summary=page[entry]['summary'], … -
Trouble finding page. Django url / views
this is the first time i had to ask something at stackoverflow, i'm both exited and scared, i don't know why. I'm writing a django app that just hosts web posts. The page is divided in three (3) categories (Index, lkmi and chiqung). Each post has a category (lkmi or chiqung). On the INDEX page you can see all the posts. On the LKMI page you can see only the lkmi posts. On the CHIQUNG page you can see only the chiqung posts. All is controlled just by ONE VIEW called "index_page", wich receives an argument called "cat" that is the url from one of the categories (index, lkmi, chiqung). Based on that it dictates wich posts to load. * NOW THE PROBLEM * I can't find why, but i'm only having trouble loading the lkmi section. The index page and the chiqung_page loads perfectly, but i'm having a "Page Not Found (404) Request Method: GET Request URL: http://127.0.0.1:8000/lkmi/ Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order: admin/ [name='index_page'] post/ [name='post_detallado'] ^ckeditor/ The current path, lkmi/, didn't match any of these. " I'll leave here the models, views and urls. Models class Category(models.Model): name … -
How can I host django web application on cpanel?
I am unable to host django application on cpanel.After doing whole setup I am facing 503 Service Unavailable The server is temporarily busy, try again later! -
A new table for each user created
I am using Django 3.0 and I was wondering how to create a new database table linked to the creation of each user. In a practical sense: I want an app that lets users add certain stuff to a list but each user to have a different list where they can add their stuff. How should I approach this as I can't seem to find the right documentation... Thanks a lot !!! -
Getting an Error whenever installing using pip3 command
I am a newbie on Django framework, I tried to install PostGreSql as database but after running python3 manage.py runserver command, it throws me an error.I have attached the image of the error it shows. Please help me out. Error Shown When Running Server -
How to display django tags in update form (django-taggit)?
I made a basic blog post app in django and I'm using the django-taggit project (https://github.com/jazzband/django-taggit) to create taggable Model objects. However, tags show up as a query set in my update form field: <QuerySet[<Tag:wow]> Here is what my html looks like: <input type="text" name="tags" data-role="tagsinput" class="form-control" id="tags" name="tags" value="{{ post.tags.all }}"> I know there's a way to loop through the tags when displaying them, but is there a way to loop through them within the form? I'm using a single text field to add tags separated by a comma using this tutorial: https://dev.to/coderasha/how-to-add-tags-to-your-models-in-django-django-packages-series-1-3704 I don't have an issue saving tags. My only issue is displaying tags that already exist in an editable field on my update form. thanks! forms.py: from taggit.forms import TagWidget class PostForm(ModelForm): class Meta: model = Post widgets = {'content_text': forms.Textarea(attrs={'cols': 80, 'rows': 80}), 'tags': TagWidget(), } fields = ['title', 'video_URL', 'content_text', 'score', 'tags',] -
method not allowed:POST
my code show errors: method not allowed: POST method not allowed: /home/ while running the server I couldn't find where the error is and whenever I click search in my html form it again reidirects me to http://127.0.0.1:8000/home/ here is my app's view.py class HomePageView(TemplateView): template_name = 'home.html' class ResultPageView(TemplateView): template_name = 'results.html' def search(request): if request.method == 'POST': MYSearch = Searchform(request.POST) if form.is_valid(): return redirect('/thanks/') else: MYSearch = Searchform() return render(request, 'results.html',{"MYSearch":MYSearch}) forms.py class Searchform(forms.Form): source = forms.CharField(max_length=100) destination = forms.CharField(max_length=100) urls.py urlpatterns = [ path('results/', ResultPageView.as_view(), name='results'), path('home/', HomePageView.as_view(), name='search'), ] -
How to input the image file from Django Admin to the html
if we don't use for, we can directly write the image address like '/img/1.jpg', but what if I already use for? what should i write? here is my directory of my images here is my django/admin, which is where my image has been uploaded on django / admin here is my html file {% for product in products %} <section id="card"> <div class="container"> <div class="row"> <div class="col"> <div class="card" style="width: 18rem;"> <img src= '(what should i write here?)' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.Description }}</p> <a href="#" class="btn btn-primary">Contact Us</a> </div> </div> </div> </div> </div> </section> {% endfor %} -
Multiple lookups in a Django view
I have this models.py: class Work(models.Model): creator = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name = 'creator') class Event(models.Model): repertoire = models.ManyToManyField(Work, blank=True) Now, in my template I'd like to show all the events containing the works which is present in the repertoire field of an event for a specific creator. So: views.py: context['events'] = Event.objects.filter(repertoire__work__creator_id=1) # why is this not possible? The event 'Great event' has in repertoire: song 1, by John song 2, by James song 3, by Jonathan In John, James, and Jonathan's profile page I want to show the Great event details, because they have one of their piece performed in that date. -
The empty path didn't match any of these, cant figure out
urls.py ''' from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from expense.views import expense_upload urlpatterns = [ path('admin/', admin.site.urls), path('upload-csv/', expense_upload, name="expense_upload") ] ''' views.py ''' import csv, io from django.shortcuts import render from django.contrib import messages # Create your views here. #parameter named request def expense_upload(request): #declaring template template = "expense_upload.html" data = Expense.objects.all() #prompt is a context varibale that can have different values depending on their context prompt = { 'order': 'Order of the CSV should be Month, Date, Description, Category, Withdrawal, Deposit, Paid_by, Purpose', 'expenses': data } #Get request returns the value of the data with the specified key. if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] #lets check if it is a csv file if not csv_file.name.endswith('.csv'): messages.error(request, 'Please upload a valid csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = Expense.objects.update_or_create( MONTH = column[0], DATE = column[1], DESCRIPTION = column[2], CATEGORY = column[3], WITHDRAWAL = column[4], DEPOSIT = column[5], PAID_BY = column[6], PURPOSE = column[7] ) context = {} return render(request, template, context) ''' templates/expense_upload.html Title {% if messages %} {% for message in messages … -
Django REST API POST pandas dataframe
I've seen several posts about Pandas dataframes and Django, but couldn't relate any to my specific problem. I'm trying to allow a user to manually create a dataframe in Python , and then make a Django API call to upload that dataframe to my Django site. I can get this to work if the user specifies a filepath, but not manual data entry. My current API Python call looks like: def upload_document(user_token, filename, file_path): url = 'https://www.website.com/upload/' + filename + '/' try: response = requests.post( url, files = {'document': open(file_path, 'rb')}, headers = {'Authorization': 'Token'+ ' ' + user_token} ) return(response) except: return('unable to upload document') My URL is url(r'^upload/(?P<filename>.+)/$', DocumentUpload.as_view(), name = "document-upload"), It is uploading to a model, called Document. The API view is class DocumentUpload(APIView): permission_classes = (IsAuthenticated, ) parser_class = (FileUploadParser,) def post(self, request, filename, format = None, ): user = self.request.user filename = self.kwargs['filename'] file_serializer = FileSerializer(data=request.data, context={'request': request}) if file_serializer.is_valid(): try: #file_serializer.uploaded_by = uploaded_by file_serializer.filename = filename file_serializer.save(filename = filename) return Response(file_serializer.data, status=status.HTTP_201_CREATED) except: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) My serializer is class FileSerializer(serializers.ModelSerializer): uploaded_by = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Document fields = ("id", "filename","document", "uploaded_by") I can also post the … -
Can I automate a web scraping task that updates the django database?
I am working on an application that works with data which I have previously scraped from another website using Selenium. In order for my app to always work with the most up-to-date data, I would like to set up a scheduled task that runs maybe twice a day to execute the script responsible for scraping said website. Now I looked into this a little bit and see a lot of mentions of Celery as a scheduling tool. I was wondering whether it would be feasible for Celery to take care of running a Selenium driver. I am planning to deploy this application to heroku and ideally the updating of the database would be fully automated once the application is live. Can anyone confirm that this is feasible and potentially point me to some resources that will get me started? Maybe I am completely off track here and there would be a better way to do this? Thank you