Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"name 'log' is not defined" error django python
I'm getting the error "name 'log' is not defined". Below is my code, but I have almost the exact same code on a different file which works fine. from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, HttpResponseRedirect, JsonResponse import json from .models import * import os, sys # Create your views here. def count(request, start, step): try: stop = 100 count_list = [] while(start<stop): count_list.append(start) start = start + step return count_list return JsonResponse(count_list) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() other = sys.exc_info()[0].__name__ fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] errorType = str(exc_type) return JsonResponse({"isError": True, "error":str(e), "errorType":errorType, "function":fname, "line":exc_tb.tb_lineno, "log":log}) -
Bootstrap-select widget when cloned to be used in a dynamic django 2 formset doesn't work right/won't show up?
I followed this tutorial to add a formset to my django2 project that can add and delete forms. For my project I have a markings form where a user can select from a large amount of markings to add to a image. The problem arises however that since I have a bootstrap-select widget that the new cloned widgets that are made when adding a form is either using the first selects's dropdown searchbar and don't have any choices in them(i.e. they are not initialized to be their own, perhaps cause the DOM is not refreshing?) or when I try to initialize them using newElement.find('.bootstrap-select').replaceWith(function() { return $('select', this); }) newElement.find('.selectpicker').selectpicker('render'); where newElement is my cloned element from var newElement = $(selector).clone(true); the widget just does not display at all. Without me trying to re-initialize the widgets they appear like this, blank with no choices: https://imgur.com/7rfjA6t When I try to re-initialize them they are not appearing: https://imgur.com/j8aCSLc Here is my javascript add a form functions $(document).on('click', '.addMarkingRow', function(e){ e.preventDefault(); cloneMore('.markingRow:last', 'form'); return false; }); function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() { var name = $(this).attr('name') if(name) { name = name.replace('-' … -
Filter Value Displaying Strange in Django
I am using a filter and .aggregate to sum up the value of a column 'cases' in my 'manifests' model. When this displays in the template it gives me the correct amount, but when the page displays it shows as, for example, "{'cases__sum': 1192}" . The number 1192 there is indeed the sum, but I don't want the rest of the text to show to the user! How can I stop this and get just the number? VIEWS.PY def add_manifest(request, reference_id): form = CreateManifestForm(request.POST or None) if request.method == "POST": if form.is_valid(): instance = form.save(commit=False) try: order = Orders.objects.get(id=reference_id) instance.reference = order except Orders.DoesNotExist: pass instance.save() form = CreateManifestForm(initial={'reference': Orders.objects.get(reference=reference_id)}) reference = request.POST.get('reference') manifests = Manifests.objects.all().filter(reference=reference) total_cases = Manifests.objects.filter(reference=reference).aggregate(Sum('cases')) #totaling the cases for the readonly field totalCNF = 0 for item in manifests: totalCNF += item.cases * item.CNF context = { 'form': form, 'reference_id': reference_id, 'manifests' : manifests, 'total_cases': total_cases, 'totalCNF': totalCNF, } return render(request, 'add_manifest.html', context) ADD_MANIFEST.HTML <div class="column"> <label for="form.reference" class="formlabels">Case Total:</label><br> <input type="text" value="{{ total_cases }}" readonly> </div> I just want the number not the whole reference to display in this html input box -
how to fix an error when installing mysqlclient
i can't install mysqlclient Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/suainul/dev/Env/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-dcdyrtea/mysqlclient/setup.py'"'"'; file='"'"'/tmp/pip-install-dcdyrtea/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-o6fcabnw --python-tag cp37 cwd: /tmp/pip-install-dcdyrtea/mysqlclient/ Complete output (31 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.7 creating build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/init.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.7/MySQLdb creating build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-3.7 creating build/temp.linux-x86_64-3.7/MySQLdb x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,4,2,'post',1) -D__version__=1.4.2.post1 -I/usr/include/mysql -I/usr/include/python3.7m -I/home/suainul/dev/Env/include/python3.7m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.7/MySQLdb/_mysql.o MySQLdb/_mysql.c:37:10: fatal error: Python.h: Tidak ada berkas atau direktori seperti itu #include "Python.h" ^~~~~~~~~~ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ERROR: Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing … -
Sequel -C copy database runs succesfully but does not copy any of the records in any table
I am trying to copy my sqlite3 database to a postgresql database. It runs succesfully, but no data is inserted into the tables. What is the cause? sequel -C sqlite:db.sqlite3 postgres://username:password@localhost/database Databases connections successful Migrations dumped successfully Tables created Begin copying data Finished copying data Begin creating indexes Finished creating indexes Begin adding foreign key constraints Finished adding foreign key constraints Primary key sequences reset successfully Database copy finished in 1.0044088 seconds -
Having two different forms in a Django template
In my project, i have a template where i'm trying to put two forms for different use cases. I've never come across this problem before, so i don't really know where to go from here to use two forms in the same page. At first i thought of creating another view to handle each form, but i think that this solution would create problems with the rendering of my templates, other than not being sustainable if i should have this problem again with another template. After making some research, i found a solution but it works for class based views, but i'd like to avoid that since my view is already a function based view, and i would have to make a lot of changes in my code. Would it be possible to solve this problem with a function based view? Every advice is appreciated First field class FirstForm(forms.ModelForm): firstfield = forms.CharField() secondfield = forms.CharField() class Meta: model = MyModel fields = ("firstfield", "secondfield") def save(self, commit=True): send = super(FirstForm, self).save(commit=False) if commit: send.save() return send** Second Form class SecondForm(forms.ModelForm): firstfield = forms.FloatField() secondfield = forms.Floatfield() thirdfield = forms.CharField() class Meta: model = MyModelTwo fields = ("firstfield", "secondfield", "thirdfield") def … -
Django query - get parent object in annotated count filter
I have 3 models: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(db_index=True, max_length=20, unique = True) class Content(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) #User.content_set.all() returns all Content objects of the content contentURL = models.CharField(max_length=256, null=True) thumbnailURL = models.CharField(max_length=256, null=True, blank=True) second_content = models.OneToOneField('self', on_delete=models.SET_NULL, null=True, blank=True) #if this is not NULL, then the content has been uploaded with a second one and they form a pair to be retrieved together timestamp = models.DateTimeField(auto_now_add=True) class Fight(models.Model): win_content = models.ForeignKey(Content, db_index=True, on_delete=models.SET_NULL, related_name="wins", null=True) #Content.wins.all() returns all Fight objects of the content in which this content has won loss_content = models.ForeignKey(Content, db_index=True, on_delete=models.SET_NULL, related_name="losses", null=True) #Content.losses.all() returns all Fight objects of the content in which this content has lost user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) is_private = models.BooleanField(db_index=True, default=False) #we will filter those out for user quality calculations timestamp = models.DateTimeField(auto_now_add=True) I am trying to get: All the Content where second_content is not null Annotate each content with the related Fight count: once with wins, once with losses. Here is my queryset: contents = user.content_set.exclude(content__second_content=None).annotate( win_count=Count('wins', filter=Q(wins__loss_content=second_content)), loss_count=Count('losses', filter=Q(losses__win_content=second_content)) ).order_by('-timestamp') The problem is with Q(wins__loss_content=second_content). second_content is not defined, because it refers to the Fight object, not to the parent. How can I refer … -
How can I find an absolute path of the static img which I am trying to use in templates folder in django?
I am trying to access for my email template(in the templates folder) the logo which is in the static folder. Is there any way i could know the absolute path of the img? -
How to count all the users that are currently logged In ? (Django rest framework)
I am currently trying to count the users that are currently logged in. I tried many things but none of them works. The last code that i tried is : def count_currently_logged_in(request): count = Profile.objects.filter(last_login__startswith=timezone.now() - timezone.timedelta(minutes=1)).count() return Response(count, status.HTTP_200_OK) -
Python Django Errno 54 'Connection reset by peer'
Having some trouble debugging this. I get this error always when i first start my app up, then intermittently thereafter. Could someone please help me by throwing out some debugging techniques? I've tried using a proxy inspector - to no avail, i didn't see anything useful. I've tried the suggestions about setting my SITE_URL in my django settings. I've tried with and without http:// with and without the port... Here's the unhelpful error: Exception happened during processing of request from ('127.0.0.1', 57917) Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/Users/ryan/.local/share/virtualenvs/portal-2PUjdB8V/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/Users/ryan/.local/share/virtualenvs/portal-2PUjdB8V/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer The app seems to function properly even with this connection reset but it's been driving me crazy trying to debug. -
Saving a default value in a Django form
I have a Django template where i'm using two different forms: views.py def myview(request): if request.method == 'POST': form = TradingForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() messages.success(request, f"Success") # if a GET (or any other method) we'll create a blank form else: form = MyForm() context = { 'first_form': FirstForm(request.POST or None), 'second_form': SecondForm(request.POST or None), } return render(request, "main/template.html", context) form.py class FirstForm(forms.ModelForm): rate = forms.CharField() amount = forms.FloatField() class Meta: model = MyModel fields = ("rate", "amount") def save(self, commit=True): send = super(MyForm, self).save(commit=False) if commit: send.save() return send class SecondForm(forms.ModelForm): rate = forms.CharField() amount = forms.FloatField() class Meta: model = MyModel fields = ("firstfield", "secondfield") def save(self, commit=True): send = super(MyForm, self).save(commit=False) if commit: send.save() return send As you can see, those two forms are using the same model, but they have different fields, so the user will submit those fields and the data will be saved in my DB: class Trade(models.Model): amount = models.FloatField() rate = models.FloatField() formtype = models.CharField(max_length=20) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, editable=False) def save(self): # ALL the signature super(Trade, self).save() The user submits the fields amount and rate. The field user it's not submitted by the user, … -
How to prevent my page urls from URLS with variable passed to the URLconf
i;m new here, also in django developing, Lastly i tried to create an app, something like a blog. And I have created a Model with FK relations like this: Category=>Subcategory=>Post. Till here everything is fine, also when I create a Post in Admin Panel there is a char field to put the post url ex. post-nr-1 But I want to make my app URL, friendly, just Url no '/ ' (single slug) . like this click on category: main/category-title-1 click on post: main/post-title-1 So just one URL, not slashing. This is my "urls.py" urlpatterns = [ path("", views.homepage, name = "homepage"), path("register/",views.register, name = "register"), path("logout/", views.logout_request, name = "logout"), path("login/", views.login_request, name = "login"), path("<slug:single_slug>/", views.single_slug, name="single_slug"), ] This my "views.py" only single_slug function def single_slug(request, single_slug): categories = [c.category_slug for c in TutorialCategory.objects.all()] if single_slug in categories: matching_series = TutorialSeries.objects.filter(tutorial_category__category_slug=single_slug) series_urls = {} for m in matching_series.all(): part_one = Tutorial.objects.filter(tutorial_series__tutorial_series=m.tutorial_series).earliest("tutorial_published") series_urls[m] = part_one.tutorial_slug return render(request,"main/category.html",{"part_ones": series_urls}) tutorials = [t.tutorial_slug for t in Tutorial.objects.all()] if single_slug in tutorials: this_tutorial = Tutorial.objects.get(tutorial_slug = single_slug) return render(request, "main/tutorial.html", {"tutorial": this_tutorial}) return HttpResponse(f"{single_slug} does not correspond to anything!") N ow the posts and the category response ok, but if i try to … -
The Command "python manage.py runserver" is not running
While I use the command the terminal shows a Major Error:- "import sqlparse ModuleNotFoundError: No module named 'sqlparse' " -
Display modal with information from a specific button
I have a Django template that renders a little bit of data about the user. It is a for list that goes through and creates this element for each user. I want to be able to click on that and have a modal appear with all of their information. So if I click on user1 I get user1's information, and so on. I am not sure how to do this. I am currently trying to use JavaScript to do this. The problem is that I cannot get the data from the specific element into JavaScript. I have the modal working, in that it pops up. However, I cannot find a way to retrieve the data from the specific user clicked on. #dashboard.html {% for party in parties %} <div class="userInfo"> <div class="modal-btn">{{party.id}}</div> <img user="{{party}}" src="{% static 'restaurants/images/userIcon.png' %}"> <div class="userText"> <p>{{party.lastName}} </p></br> </div> <button name="remove"><a href="/restaurants/removeParty/{{party.id}}">Remove</a></button> </div> {% endfor %} I just need to get data from a specific user into the js from the specifc button clicked. Maybe there is a better way to do this? I am not sure. I just need be able to populate a modal with data from the specific user clicked. -
How do I show the comment of the content from Django?
I am use PostgreSQL on Django. I am use Django 2.2.3 and pyton 3.7 version. I want to display comments for related content. But all comments appear in all content. I made the coding based on the narration found in the link(https://tutorial-extensions.djangogirls.org/en/homework_create_more_models/). My codes: views.py def PostDetail(request, slug): post = Post.objects.filter(status=2, slug=slug) comment = Comment.objects.filter(approved_comment=True) comment_count = Comment.objects.count() if request.method == 'POST': post_id = post['id'] print('hata: ', post_id) comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.Post = post new_comment.save() return redirect('blog:post_detail', slug) else: comment_form = CommentForm() return render(request, 'single-blog.html', { 'post_details': post, 'comments': comment, 'comment_form': comment_form, 'comment_count': comment_count } ) models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = HTMLField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) model_pic = models.ImageField(upload_to='uploads/', default='upload image') class Meta: ordering = ['-created_on'] def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') # reply_to = models.ForeignKey('self', related_name='replies', null=True, blank=True) author = models.CharField(max_length=200) comment = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) comment_image = models.ImageField(upload_to='uploads/', default='upload image') def approve(self): self.approved_comment = True self.save() def __str__(self): return self.comment single-blog.html <div class="comments-area"> <h4>Comments:</h4> <div class="comment-list"> {% for comment in comments %} <div class="single-comment justify-content-between … -
Can't run django-admin startproject mysite on windows 10
I wanted to learn django but whenever i type in the command "django-admin startproject mysite" it keeps giving me an error https://i.imgur.com/wtOmVh0.png Any help please? -
DRF: Serializer Group By Model Field
I want my api to return Account objects grouped by the account_type field in the model. This is what is returned now: [{ "id": 6, "owner": 1, "account_name": "Credit Card 1", "account_type": "credit card", "created_time": "2019-07-18T02:57:44.288654Z", "modified_time": "2019-07-18T02:57:44.288842Z" }, { "id": 11, "owner": 1, "account_name": "Savings 1", "account_type": "savings", "created_time": "2019-07-18T03:00:22.122226Z", "modified_time": "2019-07-18T03:00:22.122283Z" }, { "id": 5, "owner": 1, "account_name": "Checking 1", "account_type": "checking", "created_time": "2019-07-18T02:57:28.580268Z", "modified_time": "2019-07-18T02:57:28.580305Z" }, { "id": 9, "owner": 1, "account_name": "Savings 2", "account_type": "savings", "created_time": "2019-07-18T02:59:57.156837Z", "modified_time": "2019-07-18T02:59:57.156875Z" }, { "id": 10, "owner": 1, "account_name": "Savings 3", "account_type": "savings", "created_time": "2019-07-18T03:00:12.873799Z", "modified_time": "2019-07-18T03:00:12.873846Z" }, { "id": 7, "owner": 1, "account_name": "Credit Card 2", "account_type": "credit card", "created_time": "2019-07-18T02:57:55.921586Z", "modified_time": "2019-07-18T02:57:55.921613Z" }] And I'd like it to return something like this: { "credit card": [ { "id": 6, "owner": 1, "account_name": "Credit Card 1", "account_type": "credit card", "created_time": "2019-07-18T02:57:44.288654Z", "modified_time": "2019-07-18T02:57:44.288842Z" }, { "id": 7, "owner": 1, "account_name": "Credit Card 2", "account_type": "credit card", "created_time": "2019-07-18T02:57:55.921586Z", "modified_time": "2019-07-18T02:57:55.921613Z" } ], "savings": [ { "id": 11, "owner": 1, "account_name": "Savings 1", "account_type": "savings", "created_time": "2019-07-18T03:00:22.122226Z", "modified_time": "2019-07-18T03:00:22.122283Z" }, { "id": 9, "owner": 1, "account_name": "Savings 2", "account_type": "savings", "created_time": "2019-07-18T02:59:57.156837Z", "modified_time": "2019-07-18T02:59:57.156875Z" }, { "id": 10, "owner": … -
use textbox to search multiple view functions in django
Hello I am very new to Django/python - I have a scenario where I am seeking some directional guidance/advice , so I have a basic template with a searchbox vaule = rep_date <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> <div class="row"> <div class="col-sm-2"> <h1 style="text-align:center;position:relative">MENU</h1> <nav class="navbar bg-ligh"> <form method="post" enctype="multipart/form-data" action=""> {% csrf_token %} <input type="text" class="form-control form-control-sm" value="rep_date"> <input type="submit" value="ok"> </form> <ul class="navbar-nav"> <li class="nav-items"><a href="" class="nav-link">Report 1</a></li> <li class="nav-items"><a href="#" class="nav-link">Report 2</a></li> <li class="nav-items"><a href="#" class="nav-link">Report 3</a></li> <li class="nav-items"><a href="#" class="nav-link">Report 4</a></li> <li class="nav-items"><a href="#" class="nav-link">Report 5</a></li> </ul> </nav> </div> <div class="col-sm-10"> {% block content %} {% endblock %} </div> </div> </body> </html> after the submission of the textbox i am trying to return the respective views for each report from the side nav bar, using the input value from the posted textbox to feed into the view for the final view results to render each html page sample for the view for each report: def ReportOne(request): RepOneResult = Reporttable.objects.filter(yyyy_mm=PostedVal).order_by("-approved")[:25] return render(request, "reports/RepOne.html", {'RepOneResult': RepOneResult}) So I am having issues appling the code logic along with including the form posted value = rep_val in … -
How create model field that accepts two different dict keys and values and has posibility to import data?
I'm newbie in Django. I started little project of collecting data about books - from google books api and with possibility to manualy add new postions. I don't how to deal with dictionary inside JSON, with i mean "industryIdentifiers": "publisher": "Random House Digital, Inc.", "publishedDate": "2005-11-15", "description": "\"Here is the story behind one of the most remarkable Internet successes of our time. Based on scrupulous research and extraordinary access to Google, ...", "industryIdentifiers": [ { "type": "ISBN_10", "identifier": "055380457X" }, { "type": "ISBN_13", "identifier": "9780553804577" } ], How to make manual input and import from API compatible? What kind of field should I choose in "industryIdentifiers" to input ISBN_10 and ISBN_13 with their identifiers? class Books(models.Model): title = models.CharField(max_length=250) authors = models.CharField(max_length=250) publishedDate = models.DateField(blank=True, null=True) industryIdentifiers = pageCount = models.IntegerField(blank=True, null=True) imageLinks = models.URLField(blank=True, null=True) language = models.CharField(max_length=5) -
How to make two different types of registration and login in django?
I have two different types of users employees and customers. how to make to different types of registration and login and i want to redirect them to different page. I am new in django but i want to learn this things. I had searched every where but i don't find any solutions Is this possible to make two different types of user login and registration in django? Help will be appreciated and motivation for me to learn django Thanking you all in advance -
TypeError: 'Object' object does not support item assignment
Good afternoon I am presenting the following TypeError error: 'Teams' object does not support item assignment, the question is that I am serializing my interfaces model, but I am adding another model's field through Foreign Key, but when trying to Post / Put a a record of my interfaces model, it asks me for the fields Name, Location, Category which I do not want to modify since these values are in the Equipo Model, and automatically from there they must bring those values class Equipos(models.Model): id_equipo=models.PositiveSmallIntegerField(primary_key=True) nombre=models.CharField(max_length=15) vendedor=models.CharField(max_length=10,default='S/A',blank=True) ip_gestion=models.GenericIPAddressField(protocol='Ipv4',default='0.0.0.0') tipo=models.CharField(max_length=8,default='S/A',blank=True) localidad=models.CharField(max_length=5,default='S/A',blank=True) categoria=models.CharField(max_length=10,default='S/A',blank=True) ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table = 'Equipos' class Puertos(models.Model): id_puerto=models.PositiveIntegerField(primary_key=True) nombre=models.CharField(max_length=25) ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table='Puertos' class Interfaces(models.Model): id_interface=models.PositiveIntegerField(primary_key=True) id_EquipoOrigen=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_origen') id_PuertoOrigen=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_origen',null=True,blank=True) estatus=models.BooleanField(default=False) etiqueta_prtg=models.CharField(max_length=80,null=True,blank=True) grupo=models.PositiveSmallIntegerField(default=0,blank=True) if_index=models.PositiveIntegerField(default=0,blank=True) bw=models.PositiveSmallIntegerField(default=0,blank=True) bw_al=models.PositiveSmallIntegerField(default=0,blank=True) id_prtg=models.PositiveSmallIntegerField(default=0,blank=True) ospf=models.BooleanField(default=False) description=models.CharField(max_length=200,null=True,blank=True) id_EquipoDestino=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_destino') id_PuertoDestino=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_destino') ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table='Interfaces' class EquipoSerializer(serializers.ModelSerializer): class Meta: model=Equipos fields=('id_equipo','nombre','vendedor','ip_gestion','tipo','localidad','categoria','ultima_actualizacion',) class NestedEquipoSerializer(serializers.ModelSerializer): class Meta: model = Equipos fields = ('id_equipo', 'nombre', 'localidad', 'categoria',) class PuertoSerializer(serializers.ModelSerializer): class Meta: model=Puertos fields=('id_puerto','nombre','ultima_actualizacion') class InterfaceSerializer(serializers.ModelSerializer): EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre') PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre') LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad') CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria') EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre') PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre') LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad') CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria') class Meta: model=Interfaces fields=('id_interface','id_EquipoOrigen','EquipoOrigen','id_PuertoOrigen','PuertoOrigen','LocalidadOrigen','CategoriaOrigen','estatus','etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description','id_EquipoDestino','EquipoDestino','id_PuertoDestino','PuertoDestino','LocalidadDestino','CategoriaDestino','ultima_actualizacion',) class EquiposViewSet(viewsets.ModelViewSet): queryset=Equipos.objects.all() serializer_class=EquipoSerializer class PuertosViewSet(viewsets.ModelViewSet): queryset=Puertos.objects.all() serializer_class=PuertoSerializer class InterfacesViewSet(viewsets.ModelViewSet): queryset=Interfaces.objects.all() serializer_class=InterfaceSerializer -
Do time consumption of query set matter in django?
i want to know do function model_name.objects.Filter takes the more time then the model.objects.get ? as we all see that the filter gives you the queryset but the get method gives you the single object but having queryset is not equal to having all the object even after having queryset if i select single object by slicing(without loop) or using get method to select the object i tryed to get time difference but it takes soo less time that i can't see from time import time def f1(): t0 = time() # Used filter print("Execution time of f1: {}".format(time()-t0)) def f2(): t0 = time() # Used Get print("Execution time of f2: {}".format(time()-t0)) can someone show me the difference or which is better even i think that get is better but how? -
Why isn't Django Memcached activity being logged?
I'm trying to use Memcached as my main cache for a Django project. However, when I enter some data into my cache to ensure that it's working properly, nothing is being logged into my log file. Here are my Django settings: # settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_SECONDS = 300 CACHE_MIDDLEWARE_KEY_PREFIX = '' MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', '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', 'django.middleware.security.SecurityMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ) Here is my Memcached configuration: # /etc/memcached.conf -d logfile /var/log/memcached.log -vv -m 64 -p 11211 -u memcache -l 127.0.0.1 I created the logfile /var/log/memcached.log and gave it owner 'memcache', group 'adm' and permissions 0644. I've confirmed memcached is running and listening on its port: $ netstat -tupan | grep 11211 tcp 0 0 127.0.0.1:11211 0.0.0.0:* LISTEN 20655/memcached tcp 0 0 127.0.0.1:11211 127.0.0.1:53822 ESTABLISHED 20655/memcached tcp 0 0 127.0.0.1:53822 127.0.0.1:11211 ESTABLISHED 22403/python To test Memcached with Django I ran the following commands: python manage.py shell from django.core.cache import cache cache.set('my_key', 'hello world!', 30) cache.get('my_key') # Returns 'hello world!' However, after running this command, the memcached log file is still empty when it should contains the get and set I just ran. What am I missing? … -
Can a Websocket message from the server be spoofed?
I am creating a multiplayer game where users have the option to move up/down/left/right. When a user makes a movement, this movement is sent to the (websocket) server so the opponent can see where the other user is. I'm wondering if these messages that contain user movements can be spoofed? If so, I will have to think of a new method. Thanks in advance -
Problem with getting post data from user and saving it to sessions in django
I'm working on my django-shop project. I have adding to cart view function. Now I want to upgrate it by adding product to cart with user selected quantity. I'm trying to get quantity from form and send it to cart view. But it doesn't work. How can I send recieved data to cart_form input value? Sorry for my bad English Here is my add_to_cart_form <form action="" method="POST" id="product-quantity"> <label for="product-quantity">Количество:</label> <input class="product-quantity-input" type="number" name="quantity" value="1" step="1" min="1" max='10' data-id='{{ item.id }}'> <button type="submit" class="btn add-to-cart-btn btn-sm" data-slug='{{ product.slug }}'>В корзину <img src="{% static 'img/shopping-cart.png' %}" class="shopping-cart-icon-in-btn"> </button> </form> Here is my cart_form <td class="text-center cart-table-info"> <form action="" method="GET"> <input class="cart-item-quantity" type="number" name="quantity" value=" recieved quantity from add_to_cart_form" step="1" min="1" max='10' data-id='{{ item.id }}'> </form> </td> Here is views.py def getting_or_creating_cart(request): try: cart_id = request.session['cart_id'] cart = Cart.objects.get(id=cart_id) request.session['total'] = cart.items.count() except: cart = Cart() cart.save() cart_id = cart.id request.session['cart_id'] = cart_id cart = Cart.objects.get(id=cart_id) return cart def cart_view(request): cart = getting_or_creating_cart(request) categories = Category.objects.all() context = { 'cart' : cart, 'categories' : categories, } return render(request, 'ecomapp/cart.html', context) def add_to_cart_view(request): cart = getting_or_creating_cart(request) product_slug = request.GET.get('product_slug') quantity = request.POST.get('quantity') product = Product.objects.get(slug=product_slug) cart.add_to_cart(product.slug) new_cart_total = 0.00 for item in cart.items.all(): …