Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing Django View data fro JavaScript using Fetch Api
I'm trying to get data from Django view using fetch API but the fetch API isn't reaching the Django view. function connect(username) { alert('connect'); let promise = new Promise((resolve, reject) => { // get a token from the back end let data; alert("before append") // data.append('csrfmiddlewaretoken', $('#csrf- helperinput[name="csrfmiddlewaretoken"]').attr('value')); alert("vc") fetch("/videocall/", { method: 'POST', // headers: { // "X-CSRFToken": getCookie("csrftoken"), // "Accept": "application/json", // "Content-Type": "application/json" // }, headers:{ 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', //Necessary to work with request.is_ajax() 'X-CSRFToken': csrftoken, }, //credentials: "same-origin", body: JSON.stringify({'username': username}) }).then(res => res.json()).then(_data => { // join video call alert("Joint") data = _data; return Twilio.Video.connect(data.token); }).then(_room => { alert("room") room = _room; room.participants.forEach(participantConnected); room.on('participantConnected', participantConnected); room.on('participantDisconnected', participantDisconnected); connected = true; updateParticipantCount(); connectChat(data.token, data.conversation_sid); resolve(); }).catch(e => { alert("catch") console.log(e); reject(); }); alert(promise) }); return promise; }; Here's my django view def videocall(request): print("Trying to login") if request.method == "POST": print("Trying to login") It's not even printing trying to login which i printed in django view. I think there's some problem in URL in fetch. I'm new to Django please help me in this regard -
Multiple classes with the same name firing on a single class click
I have the script below to like or unlike a particular post, but the posts are displayed using a for loop in Django so they all have the same class. When an upper like button is clicked, all of the remaining buttons are also clicked which I suspect is due to the jquery. I tried the solution in this thread to add StopPropagation and ImmediatePropagation but it's not working jQuery $(".class").click(); - multiple elements, click event once The Jquery code $('a.like').on('click', function(event){ event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation(); $.post('{% url "posts:post_like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); // toggle data-action $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); // toggle link text $('a.like').text(previous_action == 'like' ? 'Unlike' : 'Like'); // update total likes var previous_likes = parseInt($('span.count .total').text()); $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1); } } ); }); In the image, all three of the 'like' links would change to unlike when a single one is clicked [![Image of the output][1]][1] [1]: https://i.stack.imgur.com/qXuwz.png -
django remove the `Superuser status`
how to remove the superuser status in creating an admin user in django admin?, i mean for example, i am Staff status and i have a permission to create another user, as a Staff status admin i dont want to see the Superuser status in creating user. please see the picture below from django.contrib import admin from .models import Customer, UnitMasterlist, ProductCategory, Product, Logo, StoreName,Banner,Customer_Cart from import_export import resources from import_export.admin import ImportExportModelAdmin class Customer_CartResource(resources.ModelResource): class Meta: model = Customer_Cart fields = ('id', 'profile', 'products', 'Customer_Checkout_Detail', 'quantity', 'unitmasterlist', 'unitprice', 'discount_percentage' , 'discount_price', 'total_amount', 'created_at','updated_at',) @admin.register(Customer_Cart) class ProductAdmin(ImportExportModelAdmin): list_display = ('id', 'profile', 'products', 'Customer_Checkout_Detail', 'quantity', 'unitmasterlist', 'unitprice', 'discount_percentage', 'discount_price', 'total_amount', 'created_at','updated_at',) ordering = ('id',) list_filter = ("profile", "products") resource_class = Customer_CartResource note that is my all code in my admin.py, please bear with me, i am new in django enter image description here -
How to serialize some nested relational models in django using rest?
I have some django models with different relations to each other (i.e. Many-to-many, Foreinkey). Now, I want to serialize them using djnago-rest. Here's an example of my models and their relations: class CommonFieldsAbstarct(models.Model): name = models.CharField(max_length=30, unique=True) class ServerModel(CommonFieldsAbstarct): server_ip = models.GenericIPAddressField(default='172.17.0.1') server_port = models.IntegerField(default='9001') class SNMPLineModel(CommonFieldsAbstarct): ip_address = models.GenericIPAddressField() port = models.IntegerField(default=161) class SNMPModel(CommonFieldsAbstarct): # target line = models.ForeignKey(SNMPLineModel, on_delete=CASCADE) servers = models.ManyToManyField(ServerModel) class MetaDataModel(models.Model): key = models.CharField(max_length=20) value = models.CharField(max_length=20) snmp_device = models.ForeignKey(SNMPModel, on_delete=CASCADE) Before, I used to use this way to create json manually: def meta_data_json(meta_data): meta_data_list = [] for meta in meta_data: meta_data_list.append({ meta.key: meta.value }) return meta_data_list def server_json(servers): return [{'ip': server.server_ip, 'port': server.server_port} for server in servers] def create_json(): snmp = SNMPModel.objects.filter(name__contains='a-name') return { 'name': snmp.name, 'address': snmp.line.ip_address, 'port': snmp.line.port, 'servers': server_json(snmp.servers.all()), 'meta_data': meta_data_json(MetaDataModel.objects.filter( snmp_device=snmp.pk ) ), 'device_pk': snmp.pk } My Question: Now, how can I create such an above json through django-rest-framework instead? I don't have any problem with many-to-many. In fact, my problem is with their foreignkey(s). And here is what I've done so far: serializers.py from rest_framework import serializers class MetaDataSerializer(serializers.ModelSerializer): class Meta: fields = [ 'id', 'key', 'value', ] model = MetaDataModel class ServerSerializer(serializers.ModelSerializer): class Meta: fields = [ 'id', … -
AttributeError: 'str' object has no attribute 'as_widget'
I am trying to have more control of my Django forms by adding a custom filter from django import template register = template.Library() @register.filter(name='addclass') def addclass(value, arg): return value.as_widget(attrs={'class': arg}) but getting the AttributeError: 'str' object has no attribute 'as_widget' error here is my view def index(request): notes = Note.objects.all() form = NoteForm() if request.method == 'POST': form = NoteForm(request.POST) if form.is_valid(): form.save() return redirect('keep:index') context = {'notes':notes, 'form':form} return render(request,'Keep/note_form.html',context) def update(request,id): notes = Note.objects.get(id=id) form = NoteForm(instance=notes) if request.method == 'POST': form = NoteForm(request.POST, instance=notes) if form.is_valid(): form.save() return redirect('keep:index') context = {'notes': notes, 'form': form} return render(request,"Keep/update.html",context) def delete(request,id): obj = get_object_or_404(Note,id=id) if request.method == "POST": obj.delete() return redirect('keep:index') return render(request,"Keep/delete.html") PS. Before you throw me links to other similar questions, i want you to know i checked pretty much all the links and none of the solutions worked for me. Most common is this: else: form = UserForm() return render(request, 'register_user.html', {'form': form}) but as you can see, i did exact same thing but that doesn't work -
bootstrap popover with form in data-content working in Django 1.11 and 2.0 but not in Django 2.1-3.1
I have code below and it is working as it should in django 1.11 and after upgrading it works in django 2.0 but for some reason it is not working in higher versions of django starting from 2.1 till 3.1.4. <button type="button" class="btn btn-sm btn-secondary" id="dodaj-poziv-za-clanove-tijela" data-container="body" data-toggle="popover" title="Da li želite da dodate članove tijela u sastanak ?" data-content= "<form method='POST' action='{% url 'poziv_clanovi_dodaj' poziv_id=poziv.id %}'> <button type='submit' class='btn btn-success btn-sm clanovi float-right'>Dodaj</button> {% csrf_token %} </form>" > Dodaj poziv za članove tijela</button> In browser this button looks normal for working django versions 1.11 and 2.0 but in those that are not witch is every version above 2.0 including 2.1,2.2 and 3.0,3.1 it button has "> in it and after submitting i get csrf token error -
Django - [Errno 2] No such file or directory error: when attempting to save an uploaded file to a dynamic url
Models.py: class Enterprise(models.Model): name = models.CharField(max_length = 100) def __str__(self): return f"{self.id}_{self.name}" class Client(models.Model): name = models.CharField(max_length = 100) def __str__(self): return f"{self.id}_{self.name}" class Engagement(models.Model): name = models.CharField(max_length = 100 def __str__(self): return f"{self.id}_{self.name}" class StockCount(models.Model): name = models.CharField(max_length = 100) def __str__(self): return f"{self.name}" class InventoryList(models.Model): UploadedFile = models.FileField(_('Upload Inventory Listing'), upload_to = file_upload_location, validators=[validate_file_extension], max_length = 500) enterprise = models.ForeignKey('Enterprise', on_delete=models.CASCADE, related_name = 'inventorylists') client = models.ForeignKey('Client', on_delete=models.CASCADE, related_name = 'inventorylists') engagement = models.ForeignKey('Engagement', on_delete=models.CASCADE, related_name = 'inventorylists') stockcount = models.ForeignKey('StockCount', on_delete=models.CASCADE, related_name = 'inventorylists') views.py: def upload(request): if request.method == 'POST': form = InventoryListForm(request.POST, request.FILES) if form.is_valid(): # file is saved list = form.save(commit = False) list.enterprise = Enterprise.objects.get(pk = 1) list.client = Client.objects.get(pk = 1) list.engagement = Engagement.objects.get(pk = 1) list.stockcount = StockCount.objects.get(pk = 1) list.save() return HttpResponse(f'You have just made a post request - {list.id}') else: return render(request, "observe/upload.html", {"form": form}) else: return render(request, "observe/upload.html", {"form": InventoryListForm()}) forms.py: class InventoryListForm(ModelForm): class Meta: model = InventoryList exclude = ['enterprise', 'client', 'engagement', 'stockcount'] def __init__(self, *args, **kwargs): super(InventoryListForm, self).__init__(*args, **kwargs) upload_to callable function: def file_upload_location(instance, filename): ext = filename.split('.')[-1] # return f"{instance.enterprise}/{instance.client}/{instance.engagement}/{instance.stockcount}/{filename}" # return f"{filename}" FileType = '\\Inventory List' name = str(filename) path = os.path.join(str(instance.enterprise), str(instance.client), str(instance.engagement), … -
Twitter OAuth page asks user to re-authorize app, even though they've done it before
Say a user logged into Twitter comes to my site. Assume they have authorized my app. If I send that user to the OAuth authorization page, it keeps asking the user to (re-)authorize my app, even though they've done it a million times. Is there a way to skip the authorization process if they've already done it? Here's my code: #views.py def oauth(request): auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth_url = auth.get_authorization_url() request.session['request_token'] = auth.request_token return redirect(auth_url) get_authorization_url() seems to send my user to a re-authorization page no matter how many times they've authorized my app. I need it to skip this and redirect to my callback URL if they've already granted permissions. Anyone has any tips? -
Upload multiple images for a single product in django
I have created some nice models in models.py for uploading multiple images in single products, for different products. The good thing it uses one image model for all products. Now i'm failing to create a perfect forms.py. May someone help me please. from django.db import models from django.utils.safestring import mark_safe from ckeditor_uploader.fields import RichTextUploadingField from mptt.fields import TreeForeignKey from mptt.models import MPTTModel from django.urls import reverse from django import forms from django.forms import ModelForm, Form, TextInput, Textarea def get_upload_path(instance, filename): model = instance.album.model.__class__._meta name = model.verbose_name_plural.replace(' ', '_') return f'{name}/images/{filename}' class ImageAlbum(models.Model): def default(self): return self.images.filter(default=True).first() def thumbnails(self): return self.images.filter(width__lt=100, length_lt=100) class Image(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to=get_upload_path) default = models.BooleanField(default=False) width = models.FloatField(default=100) length = models.FloatField(default=100) album = models.ForeignKey(ImageAlbum, related_name='images', on_delete=models.CASCADE) class Product(models.Model): title = models.CharField(max_length=20) album = models.OneToOneField(ImageAlbum, related_name='model', on_delete=models.CASCADE) class Vehicle(Product): STATUS = ( ('True', 'True'), ('False', 'False'), ) brand = models.CharField(max_length=30) price = models.DecimalField(max_digits=8, decimal_places=2) mileage = models.IntegerField() ... -
sqlite3 is not recognized as an external or internal command
I'm creating a poll app using django. When I try to access the database as shown in the video I get error: 'sqlite3' is not recognized as an internal or external command, operable program or batch file. I've already manually installed and set the path in environment variables but still its showing error. Thanks for the help. -
JavaScript Uncaught TypeError: Cannot read property 'style' of null: Button Onclick makes html disappear
In a django project, I've set up a JavaScript function to select/block certain pages. I have another JavaScript function for the pages that are being loaded. This function has an onclick event listener that submits text to a form field. The problem I'm having is that when I click a button to add text to a form field, the entire page disappears. Both functions are in a static file called "main.js" The exact error message showing in the console is... Uncaught TypeError: Cannot read property 'style' of null at showPage (players:6382) at HTMLButtonElement.button.onclick (players:6388) Here's the function controlling showing/blocking of individual pages. function showPage(page) { document.querySelectorAll('tbody').forEach(tbody => {tbody.style.display = 'none';}) document.querySelector(`#${page}`).style.display = 'table-row-group'; ---(This line in error message) } document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('button').forEach(button => { button.onclick = function() { showPage(this.dataset.page); ---(This line in error message) } }); }); Here's an example from the html template of a button targeted by this function. <button class="posbutton" data-page="page1">QB</button> This is the function that submits text to a form field. function myFunction(txt) { var myTxt = txt; if (txt.includes('QB')) { document.getElementById("QB_name").value = myTxt; } else if (txt.includes('RB')) { document.getElementById("RB_name").value = myTxt; } else if (txt.includes('WR')) { document.getElementById("WR_name").value = myTxt; } else if (txt.includes('TE')) { … -
test failed at `create_superuser`
I'm doing a tutorial and following the code as is, but my test failed from django.test import Client, TestCase from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email='admin@email.com', password='password123' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email='test@email.com', password='password123', name='Test user full name' ) def test_users_listed(self): """Test that users are listed on user page""" url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) Test error: ERROR: test_users_listed (core.tests.test_admin.AdminSiteTests) Test that users are listed on user page ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/core/tests/test_admin.py", line 9, in setUp self.admin_user = get_user_model().objects.create_superuser(email='admin@email.com', password='password123') AttributeError: 'UserManager' object has no attribute 'create_superuser' I'm using the following versions: Django>=3.1.4,<3.2.0 djangorestframework==3.12.2,<3.13.0 flake8>=3.6.0,<3.7.0 -
Calculation In Multiple Html Tables on a single page
Hey i want to Perform Calculations At the End of Every Table(on a footer) in a single page. Suppose i have two tables and i want to perform calculations on a Total Amount Column. How Can i do That. Using Jquery and Javascript. There Might Be More then Two Table so please be sure it works on multiple tables on a single page. These Values in HTML Table are come using (For Loop) in Django. This Image Contains 2 HTML Tables and i want calculations on both table on a total amount column. -
Django separate projects for backend and frontend with rest api
I'm building a project with Django rest api as backend and a separate django server for serving web front-end, for accessing api from frontend I'm planning to use vanilla-JS. In future I have plan to serve the api to mobile apps also. Is it a good move? any suggestions? The site is to deal with user registration, sign-in and user generated contents. Is there any problems with django as a separate frontend for rest api? -
Error when getting all model names in django app
I am using different dbs inside my django application and while db routing, i am trying to get all models using all_models = dict([(name.lower(), cls) for name, cls in app.models.__dict__.items() \ if isinstance(cls, type)]) While running migrations, i am getting error "name app is not defined". This is my routers.py from .models import * allmodels = dict([(name.lower(), cls) for name, cls in app.models.__dict__.items() \ if isinstance(cls, type)]) class MyDBRouter(object): def db_for_read(self, model, **hints): """ reading model based on params """ return getattr(model.params, 'db') def db_for_write(self, model, **hints): """ writing model based on params """ return getattr(model.params, 'db') def allow_migrate(self, db, app_label, model_name = None, **hints): """ migrate to appropriate database per model """ model = allmodels.get(model_name) return(model.params.db == db) -
how can I save form having 1 foreign key in model?
Models.py class CompanyStudents(models.Model): company = models.ForeignKey(Company, default=None, on_delete=models.CASCADE) student_id = models.CharField(default=None, max_length=100) def __str__(self): return self.student_id Forms.py class CompanyStudentForm(ModelForm): class Meta: model = CompanyStudents fields = '__all__' Views.py def applycompany(request): if request.method == 'POST': form = CompanyStudentForm(request.POST) if form.is_valid(): form.save() return redirect('success') template <form method="POST" action="{%url 'applycompany' %}"> {% csrf_token %} <input type="hidden" name="company" value="{{ comp.company_name }}" /> <input type="hidden" name="student_id" value="{{user}}" /> <input type="submit" value="Apply"/> </form> What should I do so that the form gets saved? In the template, I'm sending data of the foreign key in the input tag. What changes should I do so that it gets the required data? When I print "forms.errors" it shows "select the data for "company" which is foreign-key. -
Django save() method saving 2 out of 3 fields. No errors are found for the third but won't save
I'm trying to modify the field value upon clicking on a tokenized link. It all works as expected except one out of 3 fields does never get updated ('company_name'). The rest do update. Very simple to showcase what's happening here. models.py (relevant fields only) class CustomUser(AbstractUser): id = models.BigAutoField(primary_key=True) work_email = models.EmailField(unique=True, null=True, blank=True, default="") work_email_verified = models.BooleanField(default=False) company_name = models.CharField(name='Company Name',max_length=100, null=False, blank=True, default="") first_name = models.CharField(max_length=50, null=False, blank=False, default="") last_name = models.CharField(max_length=50, null=False, blank=False, default="") views.py class ConfirmWorkEmailView(View): def get(self, request, uidb64, token, backend='django.contrib.auth.backends.ModelBackend', *args, **kwargs): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and work_email_activation_token.check_token(user, token): user.work_email_verified = True user.first_name = 'Rodrigo' user.company_name = 'Cool' user.save() login(request, user, backend) messages.success(request, ('Your company email and name have been verified')) return redirect('home') else: messages.warning(request, ('The verification link was invalid, possibly because it has already been used')) return redirect('home') When I reproduce the user's steps and go to the tokenized link, the DB gets successfully updated to True for work_email_verified. Thinking that it'd be something related to the field I also tested changing the name to a ramdon one "Rodrigo" in this case, it turns out first_name also … -
JavaScript Uncaught TypeError: Cannot read property 'style' of null: Onclick makes page disappear [duplicate]
In a django project, I've set up a JavaScript function to select/block certain pages. I have another JavaScript function for the pages that are being loaded. This function has an onclick event listener that submits text to a form field. The problem I'm having is that when I click a button to add text to a form field, the entire page disappears. The exact error message showing in the console is... Uncaught TypeError: Cannot read property 'style' of null at showPage (players:6382) at HTMLButtonElement.button.onclick (players:6388) Here's the function controlling showing/blocking of individual pages. function showPage(page) { document.querySelectorAll('tbody').forEach(tbody => {tbody.style.display = 'none';}) document.querySelector(`#${page}`).style.display = 'table-row-group'; ---(This line in error message) } document.addEventListener('DOMContentLoaded', function() { document.querySelectorAll('button').forEach(button => { button.onclick = function() { showPage(this.dataset.page); ---(This line in error message) } }); }); Here's an example from the html template of a button targeted by this function. <button class="posbutton" data-page="page1">QB</button> This is the function that submits text to a form field. function myFunction(txt) { var myTxt = txt; if (txt.includes('QB')) { document.getElementById("QB_name").value = myTxt; } else if (txt.includes('RB')) { document.getElementById("RB_name").value = myTxt; } else if (txt.includes('WR')) { document.getElementById("WR_name").value = myTxt; } else if (txt.includes('TE')) { document.getElementById("TE_name").value = myTxt; } else if (txt.includes('K')) { document.getElementById("K_name").value … -
Django - TemplateDoesNotExist at /performance/
I am just beginner in Django. At starting i'm trying to buit a basic applications. Now faced an issue that i'm trying to load a html file named 'main.html' from **src/products/templates/products/main.html** but django loader loads it form **src\templates\products\main.html**. What can i do for it now? codes of main urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('performance/', include('products.urls', namespace='products')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) code of products applications urls.py from django.urls import path from .views import chart_select_view app_name = 'products' urlpatterns = [ path('', chart_select_view, name = 'main-product-view') ] and code of products applications views.py from django.shortcuts import render from .models import Product def chart_select_view(request): return render(request, 'products/main.html', {}) Wish i would get help form someone 🙂 Thank you Note: I've migrated applications properly -
Problem with missing Distutils folder after upgrading from Ubuntu 19.10 to 20.04
Hi I was hoping that someone can help with an issue I'm having with virtualenv, and virtualenvwrapper after upgrading from 19.10 to 20.04. I had a fully functional Django application in my Dev environment on Ubuntu 19.10, but since updating to 20.04 my virtualenv isn't working correct. Specifically it says that: FileNotFoundError: [Errno 2] No such file or directory: '/usr/lib/python3.7/distutils/__init__.py I've checked the path, and the distutils folder is missing, but I'm not sure how I go about fixing this. I was hoping that someone here could help me? There is a disutils folder in /usr/lib/python3.8, but when I copy that across to my python3.7 folder, I just get a different error Any help would be greatly appreciated, thanks in advance -
Django jinja values not passed in correctly to iframe url (open streetmap)
I have tried several ways to incorporate an openstreetmap via iframe into my django app. I can see the map fine and can zoom in or out, but it is always a map of Antigua. I want to embed a small map in my django template and pass in latitude and longitude from jinja. It makes no difference whether I pass in hard coded lon and lat or jinja, I still get the same map in openstreetmaps. I started with this template from the openstreetmaps wiki https://wiki.openstreetmap.org/wiki/OpenLinkMap : <iframe width="420" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.openlinkmap.org/small.php?lat=<LAT>&lon=<LON>&zoom=<ZOOM>" style="border: 1px solid black"></iframe> No matter whether I hard code or put dynamic values, I see a map of Antigua. I tried passing in the parameters from jinja: <iframe width="420" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://www.openlinkmap.org/small.php?lat={{ li.latitude }}&lon={{ li.longitude }}&zoom=10" style="border: 1px solid black"></iframe> That didn't work, so I tried just typing in the long and lan, and I still get Antigua: But the following works fine as a url link and passes in the correct parameters: <a href="https://www.openstreetmap.org/#map=12/{{ li.latitude }}/{{ li.longitude }}" target="_blank"><b>View Larger Map</b></a> I am new to openstreetmaps, django, and jinja and cannot see where I am making an error. -
downloading files from firebase storage, python
I'm trying to download files from my firebase storage with python, and I can't seem to figure out how. I've tried a bunch of different tutorials. So I have the credentials set up as an enviromental path: os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = credentials.json' and then based off what I've seen online, I tried this to donwnload the file from storage. In firebase storage it's just located in the base directory, so I did: storer = storage.child("project_name.appspot.com").download("path_to_file_in_storage") I already have initialized firebase using this: cred = credentials.Certificate('credentials.json') firebase_admin.initialize_app(cred) This clearly is incorrect, so how would I go about doing this? -
Delete all files and clear all references created through 'python mange.py collectstatic' command in Django
I am a newbie here and I want to know that suppose I have executed the command python manage.py collectstatic command and then I want to delete all the files created there and delete all the references created through this command. Is it possible? Because After sunning this command some of my code not working properly so I want to reverse this command or we can say I want to clear all the execution done by this command. Can I do this thing in Django? I am using Django 2.2 here. -
PostCreateView returning Page Error 404 raised by PostDetailView
I am trying add a CreateView in my Django project but I am getting a Page 404 Error raised by PostDetailView for some reason I don't undertand why. I am assuming it is because of the url pattern but I have revised it several times but still stuck. Here is the full error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/score/new_design/ Raised by: score.views.PostDetailView Here is the Models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) design = models.ImageField(blank=False, null=True, upload_to=upload_design_to) Here is the view.py class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Post fields = ['title', 'design'] success_url = '/' template_name = 'score/post_form.html' # <app>/<model>_<viewtype>.html success_message = "Your Post has been submitted" def form_valid(self, form): form.instance.designer = self.request.user return super().form_valid(form) Here is the urls.py urlpatterns = [ path('', PostListView.as_view(), name='score'), path('<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('new_design/', PostCreateView.as_view(), name='post-create'), Here is the link to the create view: <a class="dropdown-item" href="{% url 'score:post-create' %}">New Post</a> -
How to create a simple graph from dictionary in my Django project?
I created a simple dictionary in my Django view and I want to make a simple graph from it and show it in my template. The dictionary ("sum_by_date") is of working hours per date e.g. {'2020-10-09':1.5,'2020-10-10':2}. I want a graph with bars, the dates on x - axis and the hours on y-axis and a line between the dots. What is the simplest way to do so? I want something equivalent to : pyplot.bar(*zip(*sum_by_date.items())) of matplotlib.pyplot. Thank you