Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django async model update not being enacted
The SQL update does not seem to be being enacted upon, and no errors are being thrown either. Below is a simplified version of my code. For context, the "choice" field in the model is a Boolean Field with a default of False, and a user may (ideally) change this by sending a JSON package with the "CHOICE" event and "Yes" message. consumers.py import json from channels.generic.websocket import AsyncJsonWebsocketConsumer from asgiref.sync import sync_to_async from .models import Room class Consumer(AsyncJsonWebsocketConsumer): async def connect(self): self.room_code = self.scope['url_route']['kwargs']['room_code'] #Websockets connection code async def disconnect(self): #Websockets disconnect code async def receive(self, text_data): response = json.loads(text_data) event = response.get("event", None) message = response.get("message", None) if event == "CHOICE": room_set = await sync_to_async(Room.objects.filter)(room_code=self.room_code) room = await sync_to_async(room_set.first)() if (not room.choice) and message["choice"] == 'Yes': sync_to_async(room_set.update)(choice=True) #line seems to not be working elif room.choice and message["choice"] == 'No': sync_to_async(room_set.update)(choice=False) #code to send message to group over Websockets #code regarding other events async def send_message(self, res): #Websockets send message code I've tried to only include the relevant code here, but if more is needed please let me know. Thanks in advance! -
How to deal with lots of duplicated data in DB?
I'm currently building a database for a photography project and I'm having troube to decide this: There are about 3 million photographs and I'd like this to keep working even with 15 million. They are stored on disk and with paths in the DB. All of those need a caption, but captions are highly duplicated. On Average about 10 photos have exactly the same caption (same creator, same title, same date). Is it better to create one model? class Photo(models.Model): file = models.FileField() headline = models.CharField() caption = models.TextField() date = models.DateField() created_by = models.CharField() Or should I make 2 models even if it means having to create copies manually when one photo out of a group gets a different caption afterwards? class Photo(models.Model): file = models.FileField() metadata = models.ForeignKey('Metadata') def set_metadata(self, metadata): self.metadata = Metadata.models.get_or_create(metadata) class Metadata(models.Model): headline = models.CharField() caption = models.TextField() date = models.DateField() created_by = models.CharField() The most common task will be to search for pictures based on their metadata. Is creating an extra model and reducing the db table by factor 10 worth it? Or does it just introduce unnessesary complications with no benefits in performance? Thank you for your help! -
How to change datatables language on click of a button in django?
I already have the language change of my page when clicking a button, the problem is that how do I do it with dataTables? It's rare to change the entire language page and dataTables doesn't sync with the language change button. Does anyone have an idea how to do that? index.html <form action="{% url 'set_language' %}" method="POST" class="form-inline"> {% csrf_token %} <input type="hidden" name="next" value="{{ redirect_to }}"> <div> <select name="language" id="" class="form-control"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}> {{ language.name_local }} {{language.code}} </option> {% endfor %} </select> </div> <input type="submit" value="{% trans 'Go' %}" class="btn btn-danger"> </form> js <script> $(document).ready( function () { $('#datatable').DataTable({ ); } ); </script> -
Django - How to create and migrate two tables for development and production on same database? (prefix in front when running as dev)
I am trying to have two tables in one database like below based on development and production environment. development dev_my_comments production my_comments I tried using environment variable while declaring table like below class Data_Comments(models.Model): class Status(models.IntegerChoices): GENERAL = 0 YELLOW = 1 RED = 2 ord_no = models.ForeignKey(Data_Import, on_delete=models.CASCADE, related_name='comments') comment = models.CharField(max_length=500, null=True) strike_comment_type = models.IntegerField(choices=Status.choices, default=0) strike_date = models.DateTimeField(auto_now=True, blank=True) updated_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='comments_user') class Meta: db_table = 'my_comments' if settings.ENV_TYPE == 'PRO' else 'dev_my_comments' app_label = "my_app" by using this option, make migrations just renames existing tables instead of creating new... (wanted to have both the tables and want to migrate changes on both tables) is there something I am missing to make it work? -
django forms.DateInput not responding to dd/mm/yyyy format
currently I'm having issues with getting input validation working as expected with Django DateInput As per my understanding, the default format for DateInput is "%Y-%m-%d" if left untouched, however explicitly setting the format to "%d/%m/%Y" still causes validation errors. Here are some examples Input: 25/03/1981 Expected: Valid date (We expect this value to not trigger a validation error) Actual: Enter a valid date. Input: 1/07/1981 Expected: Date parsed as 1st July Actual: Date parsed as 7th January (i.e date and month are parsed in place of each other) forms.py class PatientForm(ModelForm): class Meta: # Make form look nice from here model = Patient fields = ('PAS_number', 'first_name', 'middle_name', 'surname', 'DOB', 'priority_code', 'patient_information', 'patient_status') widgets = { 'PAS_number': forms.NumberInput( attrs={'class': 'form-control'}), 'first_name': forms.TextInput( attrs={'class': 'form-control'}), 'middle_name': forms.TextInput( attrs={'class': 'form-control'}), 'surname': forms.TextInput( attrs={'class': 'form-control'}), 'DOB': forms.DateInput( format=('%d/%m/%Y'), attrs={'class': 'form-control'}), 'priority_code': forms.Select( attrs={'class': 'form-control'}), 'patient_information': forms.Textarea( attrs={'class': 'form-control'}), 'patient_status': forms.Select( attrs={'class': 'form-control'}), } -
Which better operating system (windows or linux) to use for python app on azure app service
I'am confused which opertaing system to use for my django app to deploy it on azure cloud I can't find enough information to take the best decision -
Django RestFramework nested serializer field many=false
how can I create a nested serializer field without using (many=True)? The following code works fine: from music.models import Track, Album from rest_framework import serializers class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] def create(self, validated_data): tracks_data = validated_data.pop('tracks') album = Album.objects.create(**validated_data) for track_data in tracks_data: Track.objects.create(album=album, **track_data) return album However the I cannot change the json payload as it comes from a 3rd part app, and the field "tracks" in the example should be "track" and POST just one object. This json works fine: { "album_name": "Black Album", "artist": "Metallica", "tracks": [ { "order": 1, "title": "Enter Sandman", "duration": 245 }, { "order": 2, "title": "Sad but True", "duration": 264 }, { "order": 3, "title": "The Unforgiven", "duration": 159 } ] } but I need to get this json working, one object, without the square brackets []: { "album_name": "Black Album", "artist": "Metallica", "tracks": { "order": 1, "title": "Enter Sandman", "duration": 245 } } I've tried to remove the (many=True) but I receive either the following errors: Got AttributeError when attempting to get a value for field `order` on serializer … -
Redirect a user from www.abcd.in to www.abcd.com with nginx and django app automatically
I have a unique query: There is a website is hosted on Digitalocean Droplet with a certain IP. There is a abcd.com domain and a abcd.in domain. Currently the nginx vhost is containing the abcd.com domain ServerName with the IP of the droplet. Also both abcd.com and abcd.in have the same IP addresses configured by the previous server admin. I want a way such that when I open up abcd.in domain, it should redirect to abcd.com automatically. What is the change required to be done in the Nginx server block for the same ? Or can I change directly on digitalocean itself in it's Domain Configuration. The base stack is Django App with Python Stack. -
How can I link styles.scss file with django templates?
I just facing a silly problem. I can't link styles.scss file with django template from the static folder. This method not working here {% static '/css/style.scss' %}. Now, what will have to do for linking .scss file? -
Saving Django data from forms to sqlite database
What I have here is basically recipes which have to be saved in a database with many to one relationship between hops, fermentables etc. and main recipe which includes the name type and so on. What we have is the user fills in the forms and then with this information we are calling this in the view.py file: def saveRecipe(request): try: data=json.loads(request.read()) recipe = Recipes.create(attr=data) recipe.name = data["name"] recipe.addYeast(items=data["yeast"]) recipe.addFermentables(items=data["fermentables"]) recipe.addHops(items=data["hops"]) recipe.addMashStep(items=data["mash"]) return HttpResponse(serialize('json', [recipe]), content_type='application/json') except: return HttpResponse("error") Now this leads us to the models.py file: class Recipes(models.Model): name = models.CharField(max_length=120, default='') pub_date = models.DateTimeField('date published') style = models.CharField(max_length=200, default='') brewer = models.CharField(max_length=100, default='') type = models.CharField(max_length=20, default='All Grain') version = models.CharField(max_length=20, default='1') batch_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_time = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) efficiency = models.DecimalField(decimal_places=1, max_digits=4, default=75.0) ibu = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) abv = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) notes = models.TextField(default='') carbonation = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) primary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) secondary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) __fermentables = [] @classmethod def create(cls,attr): recipe = cls() # do something with the book for k in Recipes._meta.fields: if k.name in attr: setattr(recipe,k.name,attr[k.name]) return recipe @classmethod … -
django unit test admin StackedInline with post function using reverse function
I'm working on unit test and want to test the admin dashboard where I have a user information with inline models. I don't want how to fill data to those models. this is test for the admin: def test_user_admin__create(superuser, client): client.force_login(superuser) phone_number = factory.Faker._get_faker().phone_number() password = factory.Faker._get_faker().password() response = client.post( reverse("admin:users_user_add"), { "phone_number": phone_number, "password1": password, "password2": password, "is_superuser": True, "is_staff": True, }, follow=True, ) the models: class User(AbstractUser, PermissionsMixin): phone_number = PhoneNumberField(unique=True) email = models.EmailField("Email address", unique=True, null=True, blank=True) password = models.CharField(_("password"), max_length=128) first_name = models.CharField(_("first name"), max_length=150, blank=True) last_name = models.CharField(_("last name"), max_length=150, blank=True) class Address(models.Model): label = models.CharField(max_length=200) user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="addresses") is_default = models.BooleanField(default=False) street = models.CharField(_("Street"), max_length=200) and the registration is done like that: class UserAddressInline(admin.StackedInline): model = Address extra = 0 class UserAdmin(admin.ModelAdmin): add_form = CustomUserCreationForm form = UserChangeForm inlines = [ UserAddressInline, ] admin.site.register(User, UserAdmin) admin.site.register(Address, AddressAdmin) I want to test the admin dashboard and fill data to the model User and the Addresses using the function test_user_admin__create -
how do i solve tuble object has no attribute after i run my django prject
I have created django project and starting the development. there were no issue as i test it but after i visit the developement server I get the error of tuple object has no attribute even though there is no tuble variable whatsoever -
How to store list of JSON data in a Django model?
What is the best way to store a list of JSON dictionaries in a Django model field? I am creating a transaction application for shops and I am trying to store the items of each order in a field without relying on relational models. Each item in this list will have a name, quantity and unit_price. For example: [ { "name": "Product #1", "quantity": 1, "unit_price": 25.0 }, { "name": "Product #2", "quantity": 1, "unit_price": 50.0 } ] I am using a PostgreSQL database, but I've heard it's bad practice to use database-specific fields, such as ArrayField. What would be the best way to go about this and that would also keep the DRF serialization as simple as possible? -
Get list of Array requested by ajax in a django view
let's take this ajax request in a django template: list_of_array = [{name1,value1},{name2,value2},{name3,value3}] $.ajax({ type: 'GET', url: myview_url, data: { my_list: list_of_array, }, dataType: 'json', success: function (response) { do something } }, error: function (error_data) { console.log("error") console.log(error_data) } }) Then, in the view under myview_url, I try to do something with 'my_list' in data. Like so: def myView(request): list = request.GET.getlist('my_list[]') do something... ... response_data = { "list": list, } return JsonResponse(response_data) but list return an empty list. If my_list doesn't contain associative array, like if it is: my_list = [1,2,3] I can get its content in my view. So, how to get the content of list that contains Array in my django view ? Thank you -
Getting CSRF token missing when submitting form data in django
I am getting CSRF token missing error everytime while submitting the form mentioned below. What might be the problem? Below is the code for my views.py file : *all imports are here # Create your views here. def takeExam(request, pk): mock = MockTest.objects.get(id=pk) context = { 'mock':mock, } return render(request, "exam/take-exam.html", context) @login_required(login_url='login') def startExam(request,pk): mock=MockTest.objects.get(id=pk) questions=Question.objects.all().filter(test=mock) if request.method=='POST': pass response= render(request,'exam/start_exam.html',{'mock':mock,'questions':questions}) response.set_cookie('mock_id',mock.id) return response @login_required(login_url='login') def calculateMarks(request): if request.COOKIES.get('mock_id') is not None: mock_id = request.COOKIES.get('mock_id') mock=MockTest.objects.get(id=mock_id) total_marks=0 questions=Question.objects.all().filter(course=mock) for i in range(len(questions)): selected_ans = request.COOKIES.get(str(i+1)) actual_answer = questions[i].answer if selected_ans == actual_answer: total_marks = total_marks + questions[i].marks std = student.CustomUser.objects.get(user_id=request.user.id) result = Result() result.marks=total_marks result.exam=mock result.student=std result.save() return HttpResponseRedirect('view-result') @login_required(login_url='login') def resultViews(request): mocks=MockTest.objects.all() return render(request,'exam/view_result.html',{'mocks':mocks}) @login_required(login_url='studentlogin') def checkMark(request,pk): mock=MockTest.objects.get(id=pk) std = student.CustomUser.objects.get(user_id=request.user.id) results= Result.objects.all().filter(exam=mock).filter(student=std) return render(request,'exam/check_marks.html',{'results':results}) @login_required(login_url='studentlogin') def studentMark(request): mocks=MockTest.objects.all() return render(request,'exam/student_marks.html',{'courses':mocks}) My html file: {% extends 'main.html' %} {% block content %} {%load static%} <div class="jumbotron my-2 py-4" onmousedown="return false" onselectstart="return False" > <h1 style="text-align: center">{{mock.name}}</h1> <form class="form my-2" autocomplete="off" onsubmit="saveAns()" action="{% url 'calculate-marks' %}" method="POST" > {% csrf_token %} {% for q in questions%} {% if q.question %} <div class="text-danger my-3 font-weight-bold"> {{ forloop.counter }}. {% endif %} {% if q.imgQuestion %} <img src="{{q.imgQuestion.url}}" alt="imgQuestion" /> {% … -
If you see valid patterns in the file then the issue is probably caused by a circular import in django
I am getting this error "If you see valid patterns in the file then the issue is probably caused by a circular import in". I saw other stack flow questions and I know the error is coming from views.py but I cannot seem to figure out where the error is views.py/myapp from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('<h1>Hey,Welcome</h1>') urls.py/myapp from django.urls import path from myapp import views urlpattern = [ path('',views.index, name='index') ] urls.py/myproject from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('myapp.urls')) ] -
SQLAlchemy - Passing a DDL generated Primary Key to Child Model through Relationship
I currently have a parent/child relationship defined between the Invoice/Item table. When running the following code: with Session(engine) as session: invoice = Invoice(INV_STORE=99, items=[Item(LINE_ITEM=1, BARCODE=1234567), Item(LINE_ITEM=2, BARCODE=1234567)]) session.add(invoice) session.commit() I get the following error: [SQL Server]Cannot insert the value NULL into column '...' [SQL: INSERT INTO [ITEM] ([INV_STORE], [LINE_ITEM], [BARCODE]) VALUES (?, ?, ?)] [parameters: (99, 1, 1234567)] My invoice object creates perfectly, it seems the DDL generated column values are not automatically populating the child object, only the store value I passed to the Invoice object (note the lack of INV_NUM in the insert statement). Is there something simple I am missing? Unfortunately, the legacy database we are using requires the table relationship to be configured as such, and there is no auto-increment in place for the Invoice.INV_NUM field. Here's my model configuration: class Invoice(Base): __tablename__ = 'INVOICE' INV_STORE = Column(Integer, name='INV_STORE', primary_key=True, default=1) INV_NUM = Column(Integer, name='INV_NUM', default=text(f"(SELECT MAX(INV_NUM) + 1 FROM INVOICE WHERE INV_STORE = {INV_STORE})"), primary_key=True)) ... items = relationship('Item', backref='Invoice', primaryjoin='Invoice.INV_STORE == Item.INV_STORE and Invoice.INV_NUM == Item.INV_NUM') And the Child, Item: class Item(Base): __tablename__ = 'ITEM' INV_STORE = Column(SmallInteger, ForeignKey('INVOICE.INV_STORE'), primary_key=True) INV_NUM = Column(Integer, ForeignKey('INVOICE.INV_NUM'), primary_key=True) LINE_ITEM = Column(Integer, name='LINE_ITEM', primary_key=True) ... -
Django Rest Framework - Serializer doesn't work
I am trying to create a blog API that would consist of user posts and comment instances. I am using Django & Django Rest Framework to build the API that would return data in JSON format. Below is an example of the JSON data being returned: "id": 2, "user": 1, "user_photo": "http://127.0.0.1:8000/media/users/Forest_Me.jpg", "is_owner": true, "description": "Hey there, this is my post and I like it", "images": [ { "id": 3, "post": 2, "image": "http://127.0.0.1:8000/media/posts/foo.jpg", "comment": "This is image #1" }, { "id": 4, "post": 2, "image": "http://127.0.0.1:8000/media/posts/bar.jpg", "comment": "This is image #2" } ], "created": "2022-03-23T16:58:44.800255+03:00", "likes": [ 1 ], "comment_count": 1, "comments": [ { "id": 3, "post": 2, "text": "This is a comment on my post", "user": 1, "likes": [], "created": "2022-03-23T17:00:27.074362+03:00", "images": [ 3, <----- should be URL to the image, not just id 4 <----- should be URL to the image, not just id ] } ] } My problem is that while the Post images are returned in the JSON correctly, my PostComment images are returned just as an array of id, without the URLs. I indicated with arrows in the code where I'm trying to get an array of objects (id & URLs). I suspect … -
Why can't I "git push heroku master"?
So I'm currently trying to deploy my django app to heroku, and I'm getting an error. On my app I serve both static and media files from an AWS S3 bucket, and locally everything is working fine, but when I try to deploy to heroku I get this error: These are my settings.py: PRODUCTION = True if PRODUCTION: # AWS S3 SETTINGS AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_DEFAULT_ACL = 'public-read' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_HEADERS = { 'Access-Control-Allow-Origin': '*', } AWS_QUERYSTRING_AUTH = False AWS_LOCATION = 'static' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'joaoLina.storage_backend.MediaStorage' MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, 'media') else: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I read that sometimes this problem happens because STATIC_ROOT is not set, but that is not the case. And I know I could just do: $ heroku config:set DISABLE_COLLECTSTATIC=1 but this way the problem will still be there. I did locally: python3 manage.py collectstatic python3 manage.py test and everything went just fine with 0 … -
what is fields and field_classes in django UserCreationForm?
im new to learning django and i wanted to make signup form in django but i see this part of code and i didnt understand it what are these code doing and why we use them class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = User fields = ("username",) field_classes = {'username': UsernameField} can somebody explain what are ```fields = ("username",) field_classes = {'username': UsernameField}``` and why we use them? -
Where do I place functions for setting foreign key values in Django?
I have two functions that I would like to add to my Django project, get_netloc which would run on the the Document.source_url and return a value to input into the set_source function. The set_sorce also take a list of tuples, from the SOURCE_CHOICES in the Source model. This set_source would act like a @property setter in a class, which I have a hunch is what I need to do. I am just not sure where these functions belong and how to implement them correctly. I am even wondering if they need to be in the forms, though the documents can also come from S3 via a lambda function. Here is the code I have: from django.db import models from urllib.parse import urlparse def get_netloc(url): try: return urlparse(url).netloc except: return 'other' def set_source(netloc, list_tuples): for i in list_tuples: return netloc if netloc in i else 'other' class Source(models.Model): OTHER = 'other' STACK = 'www.stackoverflow.com' TWITTER = 'www.twitter.com' REDDIT = 'www.reddit.com' SOURCE_CHOICES = [ (OTHER, 'Other'), (STACK, 'StackOverflow'), (TWITTER, 'Twitter'), (REDDIT, 'Reddit'), ] name = models.CharField('Source Name', max_length=18, choices=SOURCE_CHOICES, default=OTHER) def __str__(self): return self.name class Document(models.Model): name = models.CharField('Name', max_length=200) full_text = models.TextField('Text', blank=True, default='') source_url = models.URLField(blank=True) source = models.ForeignKey(Source, null=True, … -
How to make turn server fast
I am working on my personal project from 2 month and i am trying to build a Video confrencing web application using django and webRTC. I am facing the esshu i.e i am using stun/turn server for connnection for diffrent network but turn server is too slow and its not good for user experience i am using some public turn server. And if i only using stun server then it also work for some specific network. Servers that i am using is let iceConfiguration = { "iceServers": [ // { url :'stun4.l.google.com:19302'}, // { url: 'stunserver.org:3478'}, { url: 'stun:stun.l.google.com:19302' }, { url: 'stun:stun1.l.google.com:19302' }, { url: 'stun:stun2.l.google.com:19302' }, { url: 'stun:stun3.l.google.com:19302' }, { url: 'turn:numb.viagenie.ca', credential: 'muazkh', username: 'webrtc@live.com' }, { url: 'turn:relay.backups.cz', credential: 'webrtc', username: 'webrtc' }, { url: 'turn:relay.backups.cz?transport=tcp', credential: 'webrtc', username: 'webrtc' }, { url: 'turn:192.158.29.39:3478?transport=udp', credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=', username: '28224511:1379330808' }, { url: 'turn:192.158.29.39:3478?transport=tcp', credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=', username: '28224511:1379330808' }, { url: 'turn:turn.bistri.com:80', credential: 'homeo', username: 'homeo' }, { url: 'turn:turn.anyfirewall.com:443?transport=tcp', credential: 'webrtc', username: 'webrtc' } ] }; And my whole code is here https://github.com/nikhilkotiya/Microsoft-Teams/tree/newbranch Please help me out for this problem. Thanks in advance. -
Django created staticfiles folder rather than static folder
I do not know why Django created a folder named staticfiles rather than static as expected. That might be the reason why I got an error after running python manage.py collectstatic: The system cannot find the path specified: 'D:...\\static' My settings file included: from pathlib import Path import os import django_heroku BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I had already tried to change 'staticfiles' to 'static' in STATIC_ROOT, but no success. Could anyone please explain why and how to create a folder name "static"? Thank you very much in advance! -
How to get rid of django comments and kj buckets while upgrading from django 1.5 to django 4
I have a Django project of 1.6 which i need to upgrade it to django 4 and python 3 while doing this i have some modules error like Django comments and kj bucket how can i get the rid of this I search on internet but i even cant any find relating kj bucket all i am getting the result for s3 bucket which is not kj bucket and the result for django comments i am getting results are applicable only for Django 2.8 means i cant use them now how can i resolve this please help. also these modules not even install able now -
While editing an existing Django model, my .save() method creates the correct object, but it doesn't seem to persist through the database
I have a project where I want to give users the ability to update some of the fields on an existing Case they have. I have set up the form and it appears to work. However, when I go to save the new, updated date, the .save() method doesn't work as expected. I do the x = case.save() command, and when I print out "x", I see the expected data that I input in the form. However, immediately after the if statement, it does not persist. The database does not update. Thoughts? relevant methods in views.py: @login_required(login_url='/accounts/login') def stopThrough(request): if request.method == 'POST': c = IDForm(request.POST) if c.is_valid(): val = c.cleaned_data['id'] urlStr = ("/polls/case/edit/" + val) return redirect(urlStr) cForm = IDForm return render(request, 'caseEdit.html', {'start': True, 'cForm' : cForm }) @login_required(login_url='/accounts/login') def caseEdit(request, id): if request.method == 'POST': check = CaseForm(request.POST) print(check) if check.is_valid(): wtf = check.save() return redirect("/polls/case/edit/0") c = Case.objects.get(victimID=id) cForm = CaseForm(instance=c) return render(request, 'caseEdit.html', {'start': False, 'cForm' : cForm }) Case model class Case(models.Model): created_date = models.DateField(auto_now_add=True) creator = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='creator', null=True) victimID = models.CharField(max_length=100) #service list functions client_intake = models.BooleanField() client_orientation = models.BooleanField() criminal_justice_system_based_advocacy = models.BooleanField() crisis_intervention_or_24_hour_hotline = models.BooleanField() dental = models.BooleanField() education = …