Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue in django squashed migration while migrating the app from django 1.11 to django 3.0
The app was running on 1.11. we are migrating it to 3.0. As it is a multi-tenanted system we use django-tenant-schema. Consider the app is running on django 1.11, I ran django migrate_schemas command, it ran all the migrations, Then I switch to different virtualenv where django 3.0 is installed but here the showmigrations command says below migration hasn't run 0023_auto_20180921_1708_squashed_0025_auto_20180921_1727 It should be same in both django versions, isn't it? In screenshot, left side is django 3.0 and right side is django 1.11 -
How to append a queryset into a list?
The error I am getting is AttributeError: 'QuerySet' object has no attribute '_meta' What I am trying to do is to get the VAttribute Objects related to given class and the AttributeValues related to PAttribute object and convert into a list ? class_id = request.GET.get('class_id') print(class_id) qs = VAttribute.objects.filter(class=class_id) print(qs, '') attribute_data = [] attribute_data_values = [] for obj in qs: attribute_data.append(obj.attribute) attribute_data_values.append(obj.attribute.attributevalues_set.all()) # the problem is here data = serializers.serialize('json', attribute_data) values = serializers.serialize('json', attribute_data_values) data = { 'attribute': data, 'values': values } return JsonResponse(data, safe=False) These are my models class VAttribute(models.Model): class = models.ForeignKey(Class, on_delete=models.CASCADE) attribute = models.ForeignKey(PAttribute, on_delete=models.CASCADE) attribute_values = models.ManyToManyField(AttributeValues) class PAttribute(models.Model): name = models.CharField(max_length=255, unique=True) class AttributeValues(models.Model): name = models.CharField(max_length=255) attribute = models.ForeignKey(PAttribute, on_delete=models.CASCADE) -
Getting cannot resolve keyword when using django filter
I'm getting this error when I'm filtering csv output by date. And I also want to ask how to output a data to csv from last mont or past 6 months? as I only have current_month & current_year Thanks! Cannot resolve keyword 'created_at' into field. Choices are: amount, id, level, report, timestamp @models.py class Rainfall(models.Model): level = models.CharField(max_length=10, blank=True, default='') amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) @views.py def export_by_month(request): response = HttpResponse(content_type='text/csv') current_month = datetime.now() writer = csv.writer(response) writer.writerow(['Level', 'Amount', 'Timestamp']) for i in Rainfall.objects.filter(created_at__month=current_month): writer.writerow(i) response['Content-Disposition'] = 'attachment; filename="rainfall.csv"' def export_by_year(request): current_year = datetime.now().year return Rainfall.objects.filter(created_at__year=current_year) -
facing a weird bootstrap behavior in chrome
I have a django-bootstrap project in which an html page has a dynamically generated table with data-toggle popovers on td elements. in firefox, opera and edge everything works perfectly fine and the popover show up, but in chrome they just don't. however when I copy paste the same code in a new blank html test page unrelated to the project it works (minus a few css issues for the rest of the page). am really out of my wits end trying to understand the behavior I tried: emptying cache and hard reload multiple time no success forcing the state to trigger popover no success no errors/warnings showing up in console restart server and dev machine no success clear a week's worth of cache and browser history check if there is a chrome extension blocking it. (none am aware of since the test page is working fine) made sure my jquery bootstrap 4 cdn's are up to date I really have no clue what to turn to to find the source of the behavior. what steps do you do you guys go through if an element is randomly not showing on your page or you going through unexpected behaviors -
Django No module named 'responsive_images'
Getting the following error when ported Django from 2.7 to 3.6 Traceback (most recent call last): File "manage.py", line 21, in <module>main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Django\CampusStore\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Django\CampusStore\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Django\CampusStore\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Django\CampusStore\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Django\CampusStore\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Program Files (x86)\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'responsive_images' -
Why is this if statement not working in Django?
I'm just trying to run an if statement in html using django in the {% %} things. The statemnet is {% if listing in watchlist %}. Even though the listing is in watchlists, it doesn't make the if statement true. I used {{ }} to see what watchlist and listing are. for {{ watchlist }} I got: <QuerySet [<Watchlists: 15: Dan1308 has added 3: The Bus (yes the cool airplane), starting at 3000 to watchlist>]> for {{ listing }} I got: 3: The Bus (yes the cool airplane), starting at 3000 here's my views.py: def listing(request, NewListings_id): user = request.user listing = NewListings.objects.get(pk=NewListings_id) comments = Comments.objects.filter(listing=listing) watchlist = Watchlists.objects.filter(user=user) return render(request, "auctions/listing.html", { "listing": listing, "comments": comments, "user": user, "watchlist": watchlist }) and here's my models.py: class Watchlists(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) listing = models.ForeignKey(NewListings, on_delete=models.CASCADE) def __str__(self): return f"{self.id}: {self.user} has added {self.listing} to watchlist" So, why is it not working? -
Unable to display JsonResponse in Django web project
I am working on a django project. I want to display the result of a query with JsonResponse, but I can only get the raw data, rather than the colourful Json response. Here is my code views.py from django.shortcuts import render from django.db import connection from django.http import JsonResponse import json # Create your views here. def index(request): return render(request, 'AppTPCC/index.html') def result(request): search_string = request.GET.get('name', '') query = 'SELECT * FROM item WHERE i_name ~ \'%s\'' % (search_string) c = connection.cursor() c.execute(query) results = c.fetchall() result_dict = {'records': results} return render(request, 'AppTPCC/result.html', result_dict) def query(request): query = """ SELECT w.w_country, SUM(s.s_qty) FROM warehouse w, stock s, item i WHERE i.i_name = 'Aspirin' AND i.i_id = s.i_id AND w.w_id = s.w_id GROUP BY w.w_country; """ c = connection.cursor() c.execute(query) results = c.fetchall() return JsonResponse(results, safe=False) urls.py from django.urls import path, re_path, include from . import views urlpatterns = [ re_path(r'^$', views.index), re_path(r'result', views.result), re_path(r'query', views.query, name='query'), ] Then when I type http://127.0.0.1:8000/AppTPCC/query in my browser, I can only get the raw data type. I am wondering how to solve this. Thanks in advance. -
Django how to get a user and send him through a form
I need to grab a logged in user and send it to the database. model user is ForeignKey and I need to join the logged sessions. this doesn't work don't overwrite it: if request.method == 'POST': form = Inzeratform(request.POST, instance=request.user) if form.is_valid(): post = form.save(commit=False) post.user = request.user.get_username() -
object not being saved on database while using Ajax on django
I have this form that uses ajax on post method when saving new todo object on database and it works fine. When I add new entry on the form, it is being saved on the database and displays the new entry on the end user. However, I made a code that whenever I clicked those tasks below(the whole div), (Grocery, eat snack, etc see the picture for reference), the object's completed attribute should be True(it means the end user is done doing the task) and the texts should have a line-through on it. But, the completed attribute of each tasks listed below is not being saved as True on the database after every time I add a new entry and click the tasks, it only adds a line-through style on text, It will only be saved when I refresh the page and then click on those tasks again. in short: working: adding new entry, it displays new entry on end user without refreshing the page not working: clicking the task to make the completed attribute True after adding new entry. it only adds line-through style on each texts. (This will work ONLY if I refresh the page and then click … -
Nested writable serializer to process flattened normalized request data
I have a nested writable serializer. class GamerSerializer(serializers.ModelSerializer): account= AccountSerializer() document = DocumentSerializer() class Meta: model = Gamer fields = [ 'chosen_game', 'gamer_experience' ] This serializers is supposed to create Account object, a Gamer object related to Account as well as Document object related to Gamer. By default the nested serializer always accepts nested objects as data like this: serializer = self.get_serializer(data= { account: {...acount}, document: {...document}, chosen_game: "Minecraft", "gamer_experience": "1 year" } ) but I want the serializer to accept normalized flattened data( we assume that names of the model attributes do not overlap). Like this : serializer = self.get_serializer(data= { account_name: '', account_type:'', document_name: '', document_file: '', chosen_game: "Minecraft", "gamer_experience": "1 year" }) How can I achieve this result ? -
Post method Forbidden (CSRF cookie not set.)
I am trying to create new post from react frontend and I am getting this error. Forbidden (CSRF cookie not set.): /blog/create/ # views.py class CreatePost(CreateAPIView): permission_classes = (permissions.AllowAny, ) queryset = BlogPost.objects.all() serializer_class = BlogCreateSerializer # urls.py path('create/', CreatePost.as_view()), But when I tested my api with Postman, it created the new post without any problem. I already tried other provided answers from stackoverflow but no luck. -
ebay python SDK with django - config file not found when addietm function is called through views.py, works otherwise
I'm building a django project where, in my views.py, I'm trying to call a function from another .py file in the same directory, which makes an api call to ebay. When I run the function inside the .py file, it works fine, but when I call it from my views.py, I get this error: 'config file ebay.yaml not found. Set config_file=None for use without YAML config.' I don't understand why this only happens when I call it from views.py? The ebay.yaml file is in the same directory as both these files. views.py from django.http import HttpResponse from django.shortcuts import render import sys from djangonautic.forms import HomeForm import _sqlite3 import os.path from djangonautic import additem #this is the file that has the function def homepage(request): if request.method == "POST": form = HomeForm(request.POST) if form.is_valid(): print("Form was valid") text = form.cleaned_data['post'] config_for_ebay = 'ebay.yaml' #config file to make api call resp_object = additem.make_api_call(text, config_file=config_for_ebay) args = {'form': form, 'text': text} context = {'title': resp_object} return render(request, "script_run.html", context=context) else: print("ewe") form = HomeForm() return render(request, "homepage.html", {'form': form, 'text': 'bla'}) additem.py from ebaysdk.trading import Connection from djangonautic import api_formatting_for_raw_html from djangonautic import get_categories #var_pics = {'Color': [x[1] for x in variations]} def … -
How to join Objects in Django with Foreign Keys 2 tables deep
I have 2 models each with foreign keys to 2 tables. I'm trying to join the 1st table to the 3rd. Here are my models: Model 1: class AppBillingBil(models.Model): id_bil = models.AutoField(primary_key=True) idtrp_bil = models.ForeignKey(AppTradingPartnerTrp, models.DO_NOTHING, db_column='idtrp_bil', blank=True, null=True) idcst_bil = models.ForeignKey(AppCustomerCst, models.DO_NOTHING, db_column='idcst_bil') idbtp_bil = models.ForeignKey(AppBillingTypeBtp, models.DO_NOTHING, db_column='idbtp_bil') class Meta: db_table = 'app_billing_bil' ordering = ['id_bil'] Model 2: class AppCustomerCst(models.Model): id_cst = models.AutoField(primary_key=True) is_active_cst = models.BooleanField() name_cst = models.CharField(max_length=50, blank=True, null=True) Model 2: class AppTradingPartnerTrp(models.Model): id_trp = models.AutoField(primary_key=True) tpid_trp = models.CharField('TPID', max_length=50, blank=True, null=True) name_trp = models.CharField('Name', max_length=50) Final Model Needed: class AppCustomerTpRel(models.Model): id_rel = models.AutoField(primary_key=True) idcst_rel = models.ForeignKey(AppCustomerCst, models.DO_NOTHING, db_column='idcst_rel') idtrp_rel = models.ForeignKey(AppTradingPartnerTrp, models.DO_NOTHING, db_column='idtrp_rel') cust_vendor_rel = models.CharField(max_length=50, blank=True, null=True) I need to join on the following criteria: idtrp_bil__id_trp = idtrp_rel idcst_bil__id_cst = idcst_rel And I need to be able to use the cust_vendor_rel field from AppCustomerTpRel in a filter query on AppBillingBil -
django-cors-header problem with authorization cookies
I am using Django base authorization to protect specific routes of my API (using @login_required decorator), and Insomnia to test them out. Using Insomnia I can login using my ```api/auth`` route and then access to every protected route of my APIs. The problem comes with React: I have my React app running on localhost:3000 and my Django APIs on localhost:8000. When I log in though the login page (made with react and react-router-dom) it just works. But after that, if I open the HomePage (which fetches data from a login_required route) I get a 404 response ( which is caused by @login_required ). I tought that the problem was because of fetch and cookies, But I can't figure out a way to solve it. It seems like Insomnia automatcally stores the cookie returned by api/login but the same doesn't happen with react. I've also already tried to set credentials to include and same-origin in my login fetch. Did someone already experienced this problem? MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... MIDDLEWARE_CLASSES = ( 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware' ) CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] CORS_ORIGIN_REGEX_WHITELIST = [ 'http://localhost:3000', ] -
How to Dynamically adding a form to a Django formset with jQuery
I want to automatically add new forms to a Django formset using jQuery, so that when the user clicks an "add" button it runs jQuery that adds a new form to the page. Django Template: {% extends 'base/base.html' %} {% load static %} {% block content %} <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script> $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> <div class="card"> <form class="form-horizontal" action="" method="post"> {% csrf_token %} <div class="card-header"> <strong class="icon-book"> User Academic Information</strong> <hr class="divider" /> </div> <div class="card-body"> <div class="card-body"> <div class="form-horizontal"> {{ employAcademicFormSet.management_form }} <div id="form_set"> {% for form in employAcademicFormSet %} {% for field in form.visible_fields %} <div class="form-group row"> <label class="col-md-3 col-form-label" for="text-input"><h6>{{ field.label_tag }}</h6></label> <div class="col-md-9">{{ field }}</div> </div> {% endfor %} {% endfor %} <div class="form-group row"> <label class="col-md-3 col-form-label" for="text-input"> </label> <input class="ml-2" type="button" value="Add More" id="add_more"> </div> </div> </div> </div> </div> <div class="card-footer"> <button class="btn btn-lg btn-primary" type="submit">Submit</button> </div> </form> </div> {% endblock %} Please help me for solve the problem... -
ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 6379) WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:56602]
Here, I need to connect another channel using web sockets in django channels. I can't connect to the another channel, it showing error like this. Can anybody please help me, I just attched my code below, kindly go through it consumers.py import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) routing.py*(In django project)* from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) routing.py*(In chat app)* from django.urls import re_path from .consumers import ChatConsumer websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$',ChatConsumer), ] views.py from django.shortcuts import render def index(request): return render(request, 'chat/index.html') def room(request, room_name): return render(request, 'chat/room.html', { 'room_name': room_name }) urls.py*(In chat App)* from django.contrib import admin … -
Enter a valid date/time in django
Everytime I select date and time, django form throws "Enter a valid date/time" error. models.py class Quiz(models.Model): .... Ending_Time = models.DateTimeField(null=True) .... forms.py class QuizForm(forms.Form): .... closing_time = forms.DateTimeField(widget=forms.DateTimeInput(attrs={'class':'form-control form-control-lg','type':'datetime-local'})) .... views.py def createquiz(request): if request.method == "POST": form = QuizForm(request.POST) if form.is_valid(): quiz_text = form.cleaned_data['desc'] closingtime = form.cleaned_data['closing_time'] newquiz = Quiz(Description=quiz_text, Ending_Time=closingtime) newquiz.save() return HttpResponseRedirect(reverse('createques')) else: form = QuizForm() return render(request, "quiz/createquiz.html", {'form': form}) -
Creating a single API with models which dont have direct relationship with each other
I have these 3 models. Among these 3 models, Flightdetails and Passenger are in relationship with the third model Booking. But the 1st and the 2nd model doesnt have any relationship. And in the frontend I have a form like that for the booking. What I want to do is create an POST API from passenger model where user can submit the passenger's info and it is booked. BUt what my senior is demanding is that in the same post api, I should also have the flight id( primary key) request, so that when I submit the form or book, it (the object) should also have its own flight id. I hope I explained well. class FlightDetails(models.Model): Flight_Name = models.CharField(max_length=200) Aircraft_name = models.CharField(max_length=200) Destination = models.CharField(max_length=200, verbose_name = "To") def __str__(self): # return self.Flight_Number return 'Flight({})'.format(self.id) class Passenger(models.Model): First_name = models.CharField(max_length=200, unique=True) Last_name = models.CharField(max_length=200, unique=True) Gender = models.CharField(max_length=50) Nationality = models.CharField(max_length=200, unique=True) Passport_No = models.CharField(max_length=200, unique=True) Passport_Exp_Date = models.DateField(blank=False) Contact_Number = PhoneField(help_text='Contact phone number') Email = models.EmailField(max_length=200, unique=True) # Customer_id = models.CharField(max_length=50) def __str__(self): return (self.First_name, self.Contact_Number) class Booking(models.Model): # Book_Id = models.CharField(max_length=50) flight_number = models.OneToOneField(FlightDetails, on_delete = models.CASCADE) Booking_Date = models.DateField(default= True, verbose_name = "Booking Date(dd/mm/yy)") customer_name_and_phone = … -
Deploy Django 1.7 application to Apache2 with WSGI
I am trying to deploy an old Django application (1.7) to the Apache2 server on Debian. I am finally able to run the app with ./manage.py runserver but I had no success in getting the mod-wsgi working. I've never wrote a server side application in Python so please forgive me if I am missing something obvious. These are the steps I followed Everything I tried is with /usr/bin/python which is 2.7 - I know, I should be using virtuelenv but I didn't want to add even more complexity to the while thing (since I am not familiar with it) installed mod-wsgi with apt-get install libapache2-mod-wsgi Add following config to the /etc/apache2/mods-enabled/wsgi.conf Apache2 restart <IfModule mod_wsgi.c> WSGIScriptAlias / /home/rosasystem.pl/public_html/rosasystem/rosasystem/wsgi.py WSGIPythonHome /usr/bin/python WSGIPythonPath /home/rosasystem.pl/public_html/rosasystem LogLevel warn <Directory /home/rosasystem.pl/public_html/rosasystem/rosasystem> <Files wsgi.py> Order deny,allow Require all granted </Files> </Directory> </IfModule> Since then, I keep getting this error message in the error.log - most of the stuff I've googled suggest that there is a Python version discrepancy between mod-wsgi and system/virtualenv Python version which in this doesn't make sense because everything is Python 2.7. [Tue Oct 06 15:13:42.946626 2020] [mpm_event:notice] [pid 17059:tid 139874785088640] AH00489: Apache/2.4.38 (Debian) mod_fcgid/2.3.9 OpenSSL/1.1.1g mod_wsgi/4.6.5 Python/2.7 configured -- resuming normal operations … -
Django Project error repormissingimports , could not be resolved
Now I'm working on main project's root urls.py file in the configuration directory my_blog, and want to import views.py file from user app, but when i can't user app in main urls file and when trying to import like;from users importenter image description here views as user_views, its showing an error -
Django and windows Server 2012
I have developed a Django project and I want to host my website on a server which has Operating System: Microsoft Server 2012 R2 . I am new to Django and kind of lost where is to start.Can anyone provide me step by step direction? -
django.core.exceptions.ImproperlyConfigured:while generating fake data
##its Models.py## from django.db import models from random import * from django_faker import Faker # Create your models here. class Blore_jobs(models.Model): date=models.DateField() company=models.CharField(max_length=100) title=models.CharField(max_length=30) eligibility=models.CharField(max_length=30) email=models.CharField(max_length=50) phone=models.IntegerField() # @classmethod # def get_or_create(cls, date, company, title, eligibility, email, phone): # pass class populator(): # from portal.models import * # import os # os.environ.setdefault('DJANGO_SETTINGS_MODULE','Jobs.settings') # import django # django.setup() def generate(self,n): fek = Faker.getPopulator() for i in range(50): fdate = fek.date() fcompany = fek.company() ftitle = fek.random.choice(('TeamLead', 'Developer', 'Tester', 'Manager')) feligibility = fek.random.choice(('Btech', 'Mtech', 'Math')) faddress = fek.address() fmail = fek.email() def indian_phone(self): fek = Faker.getPopulator() first = fek.random.randint(7, 9) last = '' for i in range(9): last = last + str(fek.random.randint(0, 9)) return int(str(first) + last) fphone = indian_phone(self) # to add fake data to db Blore = Blore_jobs.get_or_create(date=fdate, company=fcompany, title=ftitle, eligibility=feligibility,email=fmail, phone=fphone) generate(50) I cant able to add fake data to Blore_jobs Db i am getting error like: Traceback (most recent call last): File "models.py", line 7, in <module> class Blore_jobs(models.Model): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/conf/__init__.py", line 64, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: … -
Comments not visible in template even though they are saved in the database
I currently have 2 models in my App, one for uploaded files and another one for comments. I've figured out how to implement the forms on the same page and it seems to be working but for some reason, the submitted comments aren't being shown and I have no idea on how to accomplish that. Should I provide the comments in a return or seeing as that there is a ForeignKey in the Comment model this is not neccesary and the comments can be accessed through each file? # Model for all uploaded files class Uploaded(models.Model): objects: models.Manager() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users") time_uploaded = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=100) file = models.FileField(upload_to=MEDIA_ROOT) admintags = TaggableManager(blank=True, through=AdminTagsAll, verbose_name="Admin Tags") usertags = TaggableManager(through=UserTagsAll, verbose_name="User Tags") additional_description = models.CharField(max_length=50, blank=True) def __str__(self): return f"{self.description} {self.file}" # Model for comments class Comment(models.Model): objects: models.Manager() file = models.ForeignKey('Uploaded', on_delete=models.CASCADE, related_name='comments') text = models.TextField() def __str__(self): return self.text HTML template: {% for comment in comments %} <div style="border:1px solid silver; border-radius:15px; padding:15px; margin:10px 0px;"> <p class="mb-auto" style="font-size:15px;">{{ comment.text }}</p> </div> {% empty %} <div style="border:1px solid silver; border-radius:15px; padding:15px; margin:10px 0px;"> <p class="mb-auto" style="font-size:15px;">No Comments</p> </div> {% endfor %} Views.py def index(request): url_parameter = request.GET.get("q") user … -
Django Custom User UUID Duplicated (cached?)
I'm Using Django with a custom user model with custom UUID and custom user manager: class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=generate_id(), editable=False) # ... As you can see, I'm NOT using default=uuid4(). Instead I've made a function my on my own that uses uuid() to generate the custom id also using the timestamp: from datetime import datetime as dt from uuid import uuid1, uuid3, uuid4 def generate_id(): timestamp = str(dt.timestamp(dt.now())) return uuid3(uuid4(),timestamp) Now if I open the interactive shell: python manage.py shell and I call my function several time, this is what I get: >>> generate_id() UUID('bd8279f1-9b4b-3d7d-8932-f9e725f17045') >>> generate_id() UUID('0c2ec2ad-b062-3915-a9e9-22842c6f5ea2') >>> generate_id() UUID('2289202b-f252-3b27-bcae-cd44825bf4e0') >>> generate_id() UUID('88676ea9-4902-36ac-857d-929cb133089c') >>> generate_id() UUID('4a18b33e-12f0-3803-8ff0-0c4f0d1c849c') but when I try creating 2 users: from users.models import CustomUser >>> one = CustomUser.objects.create_user(email='hhh@jaja.com',password='JJlsaks16112') >>> two = CustomUser.objects.create_user(email='ttth@jija.com',password='JJlsaks16112') Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.IntegrityError: (1062, "Duplicate entry 'b448f583acfb31b7955926689b60f28a' for key 'PRIMARY'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File … -
How to set backgroundcolor and border for each array element using javascript or jquery?
I am trying to set separate background and border for each element in the array using JavaScript something like this. Until now what I have done outputis below. As I add a new element to the array, it will stretch the background. let skills = []; function displayname() { console.log(document.getElementById("namehere").value); x = document.getElementById("namehere").value; skills.push(x); console.log(skills) document.getElementById("skill-set").innerHTML = skills document.getElementById("skill-set").style.border = "1px solid blue"; document.getElementById("skill-set").style.backgroundColor = "yellow"; document.getElementById("skill-set").style.padding = "5px"; document.getElementById("skill-set").style.display = "inline-block"; document.getElementById('namehere').value = " "; } <label>Enter the skills: </label><br> <input type=t ext id="namehere" onchange="displayname()"> <div id="skill-set"></div>