Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert a query set values_list into an valid array, django
Hi I have come up with the problem that, when I do querySet = FollowModel.objects.filter(following = request.user.id).values_list('followed') lis = list(querySet) print(lis) it prints out [(2,), (1,)] Is there a way I can print out [2,1] instead? So that I can extract the posts according to the people who I follow and do something like: PostModel.objects.in_bulk(lis) Thank you!!! Also, my FollowModel looks like this: class FollowModel(models.Model): following = models.ForeignKey( ProfileModel, related_name="who_follows", on_delete=models.CASCADE) followed = models.ForeignKey( ProfileModel, related_name="who_is_followed", on_delete=models.CASCADE) follow_time = models.DateTimeField(auto_now=True) def __unicode__(self): return '{} follows {}'.format(self.following, self.followed) + ' at ' + str(self.follow_time) -
Django: __init__.py package breaks migrations
In my app, I have file structure: myapp/ ... models.py helpers/ __init__.py RandomFileName.py ... In RandomFileName.py I have helper class that generates random file names for my models: class RandomFileName(object): ... In models I want to treat helpers/ directory as a module: from myapp.helpers import RandomFileName class MyImage(models.Model): ... image = models.ImageField(upload_to=RandomFileName('images/')) ... Then, I run python3 manage.py makemigrations myapp Looks good. Then, I run python3 manage.py migrate and get an error: in Migration ('image', models.ImageField(upload_to=myapp.helpers.RandomFileName.RandomFileName('images/'))), AttributeError: type object 'RandomFileName' has no attribute 'RandomFileName' Why is the RandomFileName doubled in migrations? Where did I go wrong? -
Django Rest Framework: Shared Fields on Serializers
I have a few Serializers that share a few fields like meta_id, category_id and so on. Obviously I could just declare these on the serializer as a SerializerMethodField individually but I would like to find a way to reuse the logic, either with a Mixin, Decorator, or inheritance. How can I declare a base serializer and inherit it— while still inheriting from serializers.ModelSerializer? So that I can reuse the get_meta_id and make sure it shows up in the fields? class Foo(serializers.ModelSerializer, somethingHere?): meta_id = Serializers.SerializerMethodField() class Meta: model = Foo fields = [...] def get_meta_id(self, obj): ... Is it possible to just pass two parameters into the class -
how to search Parent object using attribute of a child object, django-filter
Context: i have a Bearing with a loot of measurements (interior, exterior, etc), but every brand put a number on that same Bearing (same combination of measurements) that is called "Equivalent". so a bearing can have one, none o many equivalents. Something like this: Now i want to filter information from all Bearing atributes, but also for the equivalent Number, i have searcher like this: filters.py: class BearingFilter(django_filters.FilterSet): class Meta: model = Bearing fields = [ 'D_INT_A', 'D_INT_A1', 'D_EXT_D', 'D_EXT_D1', 'D_ESP_B', 'D_ESP_C', 'D_ESP_T', 'N_PARTE_1', 'N_PARTE_2', 'FK_TIPO_ROD', ] views.py: def searcher(request): list_Bearing = Bearing.objects.all() list_Equiv = Equivalent.objects.all() list_Bearing_filter = BearingFilter(request.GET, queryset=list_Bearing) return render(request, 'searcher.html', {'equiv': list_Equiv , 'bearing_filter' : list_Bearing_filter }) the html is something like this: for x in bearing_filter.qs Row with Bearing Info Modal With Equivalent info for y in equiv if x.id = y.Bearing_fk y.Number - y.Brand endif endFor endfor Im still learning django + python, and i don't know how to approach this. Maybe django-filter is not good in this case i don't know -
Python Stops Running then causes memory to spike
I'm running a large Python3.7 script using PyCharm and interfaced by Django that parses txt files line by line and processes the text. It gets stuck at a certain point on one particularly large file and I can't for the life of me figure out why. Once it gets stuck, the memory that PyCharm uses according to Task Manager runs up to 100% of available over the course of 5-10 seconds and I have to manually stop the execution (memory usage is low when it runs on other files and before the execution stops on the large file). I've narrowed the issue down to the following loop: i = 0 for line in line_list: label_tmp = self.get_label(line) # note: self because this is all contained in a class if label_tmp in target_list: index_dict[i] = line i += 1 print(i) # this is only here for diagnostic purposes for this issue This works perfectly for a handful of files that I've tested it on, but on the problem file it will stop on the 2494th iteration (ie when i=2494). It does this even when I delete the 2494th line of the file or when I delete the first 10 lines of … -
Bootstrap Django: Only show Active field in tabs
I`ve got two tabs: <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="open-tab" data-toggle="tab" href="#open" role="tab" aria-controls="open" aria-selected="true">Active Projects</a> </li> <li class="nav-item"> <a class="nav-link" id="close-tab" data-toggle="tab" href="#close" role="tab" aria-controls="close" aria-selected="false">Inactive Projects</a> </li> </ul> The Model of the Application got a field {{app.is_active}}. Is Filtering the tab with a script is the best option to only show "Active projects" in the active tab and "Inactive projects" in the inactive tab? Many Thanks, -
DRF: Image vs Field naming
On my model, I have fields like photo = models.ImageField()– practically this means I can upload and set images from the admin; but from the DRF Serializer it feels more appropriate to suffix URL: photo_url = serializers.ImageField() Is there a standard way of doing this in a DRF-y way here? I could of course make the photo on my model into photo_url, but that feels a bit strange. -
Remove admin app and templates from Django if they're not being used
I'm using Django with Django-Rest-Framework. I'm not using the admin app and if I decide I don't want to use the self-documenting api pages I wouldn't be using Django templates as well. I'm debating if I should remove these built-in features (the admin app and the templates). A few questions about this: Is it okay to do this or are there any unintended consequences? Is this even worth it (are these features large enough to help performance if they're removed)? Have people done this in the past and considered it "good practice"? -
cmder virtualenv name showing
I am new to cmder, when ever I try to create virtualenv for python, django and activate it using ./Scripts/activate This is cmder : F:\python\django\tweeter λ .\Scripts\activate F:\python\django\tweeter λ This is Git bash : Ahmed@DESKTOP-VJ37FJE MINGW64 /f/python/django/tweeter $ source ./Scripts/activate (tweeter) Ahmed@DESKTOP-VJ37FJE MINGW64 /f/python/django/tweeter $ (tweeter) Ahmed@DESKTOP-VJ37FJE MINGW64 /f/python/django/tweeter $ As you can see when I use Git bash, it shows me virtualenv name when I activate it. But it not goes same for cmder. -
Django is looking at wrong urls file
I am using django 2.2 version. In my settings.py i have below setting. ROOT_URLCONF = 'project12.urls' When i try to open a page i get below warning. Using the URLconf defined in project1.urls, Django tried these URL patterns, in this order: admin/ The current path, testnow, didn't match any of these. As you can see, settings is project12.urls but it is looking for project1.urls. I changed the settings.py several times, but it is still looking for project1.urls. -
Django admin log doesnt exist
Trying to make Django project (newby) and ater creating some models Ive found that in Database django_admin_log folder doesnt exist and django.contrib.admin doesnt exist in INSTALLED_APPS as well. Any help is appreciated. -
Celery beat periodic task management won't run my function
I have some trouble setting up asynchronous tasks with celery beat. I use django 2.2.1, celery 4.4.0 and django-celery-beat 1.6.0. My objective is to run a specific function every 10 seconds. Here is how I set up my project: proj/proj/settings.py CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers.DatabaseScheduler' CELERY_TIMEZONE = 'UTC' CELERY_ENABLE_UTC = True proj/proj/celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() proj/proj/init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app') proj/proj/tasks.py @app.task def team_test(): t_all = Team.objects.all() for t in t_all: t.total = random.randint(1, 1000) t.save() Now from this point everything seems to be working fine. I am able to add tasks directly in the shell terminal with the commands: schedule, created = IntervalSchedule.objects.get_or_create(every=10, period=IntervalSchedule.SECONDS) PeriodicTask.objects.create(interval=schedule, name="team test", task='proj.tasks.team_test') I have run that command with many test functions yet and they all then appear in my database. So far so good. In order to kick off the celery beat workers I then go in my command terminal and start the workers with the command: celery -A proj beat -l debug Again, I see encouraging results: celery beat v4.4.0 (cliffs) is starting. __ … -
Django multiple templates
I'm building a site where users can view their posts Like this. After building the quizzes portion, I tabbed to "blogs" where I realized I needed to import the blogs template to use it. I'm using the quiz template already like this {% extends '../main/base.html' %} {% block title %}View Quizzes{% endblock %} {% block content %} but I need to access the blog template as well. How can I do this? Thanks! -
Update button not getting the query
thanks for your time: I've got a model that is linked to the user and the only one that can update him its his creator. untill that works fine. just the creator user can open the url update although i'm not beeing able to pass a button on the main template of the model with redirect to that update url. i'd like to know if there is a way to that button apear just to his user (if not ok, to get in just open to the matching queryset user). Or just why this button ain't working: i should get the url eg:services/parceiro/update/2 i'm beeing able to open this url if i'm the creator user but when i try to set it in a button i get this error: Reverse for 'update_parceiro2' with arguments '('',)' not found. 1 pattern(s) tried: ['services/parceiro/update/(?P[0-9]+)$'] parceiros.html: {% extends "base.html" %} {% block content %} <h1>{{parc.nome}} - {{parc.user}} - {{parc.responsavel}}</h1> <form action="{% url 'update_parceiro2' Parceiros.id %}"> <button type="submit"><i class="material-icons">sync</i></button> </form> {% endblock %} views.py: def parceirosview(request, pk=None): parc = get_object_or_404(Parceiros, id=pk) context = {'parc': parc} return render(request, 'parceiro.html', context) def get_queryset(self): return super().get_queryset().filter(parceiro__user=self.request.user) class ParceiroUpdate(UpdateView): model = Parceiros template_name = 'parceiroform.html' fields = ['nome', 'endereco', … -
Simple app to matching persons to board game
I searched the internet similar apps or some useful staf but i cant found, so i I have some python and django experience, i made blog site, and chatbot application. Now i want to make simple application with using Python and Django to choose board game from my collection to play with friends. In my app i want to have a person with preferences (example: "person 1" like strategy and coop games, "person 2" like card strategy game). Next In my base i have game with attributes (example: "Game 1" strategy, card, coop, "Game 2" is RPG game) On my website i want to have list with name of my persons and checkboxes next to everyone. I can mark checkbox next to the person and send request to my base. I want to get return with the best options to play based by personal preference and game attributes. (Example: "person 1" like strategy and coop games, "person 2" like card strategy game so my base return "Game 1" strategy, card, coop, and second "Game 3" strategy and coop) Question: How to do it, what I need to use, conditional statements, JS? I nees some exampels, similar app or useful documetation … -
How do i set enviroment variables when using python decouple
Hi I am new to python decouple and I have set it up but whenever I run the Django server I am getting raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I have a .env file in my project root as the instructions state. -
Solving the ConnectionAbortedError: [WinError 10053] without messing around with the Windows Defender and Firewall
The infamous ConnectionAbortedError: [WinError 10053] error: ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine has obviously caused a whole lot of headaches when searching the internet. There are many workarounds suggested on different forums. This post suggests that antivirus (i.e., Windows Defender) and the firewall should be disabled, which doesn't seem like a wise idea. And this post suggests adding: port 8000 to allowed rules for both incoming and outgoing traffic which I prefer not to do, simply because I don't know the implications of messing around with the firewall. The same post, however, also suggests adding the line: 127.0.0.1 localhost.localdomain localhost to the /etc/hosts, which according to this post should be \WINDOWS\system32\drivers\etc\hosts on Windows OS. However, doing so (adding the above line to the hosts file) did not help with the above error. So my questions, as the title implies, is that if there is a way to solve the said problem or circumvent it, without messing around with the Windows Defender and firewall, and jeopardizing the system's safety/security? -
getting error in installing requirement.txt file in django project [closed]
ERROR: Command errored out with exit status 1: command: 'C:\project\python project\Django-Ecommerce-master\Django-Ecommerce-master\env\Scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\bats8\AppData\Local\Temp\pip-install-7l7hxs5g\cffi\setup.py'"'"'; file='"'"'C:\Users\bats8\AppData\Local\Temp\pip-install-7l7hxs5g\cffi\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\bats8\AppData\Local\Temp\pip-install-7l7hxs5g\cffi\pip-egg-info' cwd: C:\Users\bats8\AppData\Local\Temp\pip-install-7l7hxs5g\cffi\ Complete output (23 lines): Traceback (most recent call last): File "", line 1, in File "C:\Users\bats8\AppData\Local\Temp\pip-install-7l7hxs5g\cffi\setup.py", line 127, in if sys.platform == 'win32' and uses_msvc(): File "C:\Users\bats8\AppData\Local\Temp\pip-install-7l7hxs5g\cffi\setup.py", line 105, in uses_msvc return config.try_compile('#ifndef _MSC_VER\n#error "not MSVC"\n#endif') File "c:\python38\lib\distutils\command\config.py", line 225, in try_compile self._compile(body, headers, include_dirs, lang) File "c:\python38\lib\distutils\command\config.py", line 132, in _compile self.compiler.compile([src], include_dirs=include_dirs) File "c:\python38\lib\distutils_msvccompiler.py", line 360, in compile self.initialize() File "c:\python38\lib\distutils_msvccompiler.py", line 253, in initialize vc_env = _get_vc_env(plat_spec) File "C:\project\python project\Django-Ecommerce-master\Django-Ecommerce-master\env\lib\site-packages\setuptools\msvc.py", line 171, in msvc14_get_vc_env return EnvironmentInfo(plat_spec, vc_min_ver=14.0).return_env() File "C:\project\python project\Django-Ecommerce-master\Django-Ecommerce-master\env\lib\site-packages\setuptools\msvc.py", line 1075, in init self.si = SystemInfo(self.ri, vc_ver) File "C:\project\python project\Django-Ecommerce-master\Django-Ecommerce-master\env\lib\site-packages\setuptools\msvc.py", line 547, in init vc_ver or self._find_latest_available_vs_ver()) File "C:\project\python project\Django-Ecommerce-master\Django-Ecommerce-master\env\lib\site-packages\setuptools\msvc.py", line 561, in _find_latest_available_vs_ver raise distutils.errors.DistutilsPlatformError( distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Nginx different service on subroute
I have 2 Django apps running on 8080 and 8081 ports. I use gunicorn and NGINX to serve them. Currently I have only the app on port 8080 added to NGINX, the config in sites-enabled (part of it) looks like that: location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; } Now I need to add there the second app, which is on port 8081, but so that it is served on /second_app route. So I see it like this: / -> 127.0.0.1:8080 /second_app -> 127.0.0.1:8081 However, when I do the second location to be /second_app it doesn't work, I think these two routes conflict and as long as the first on is wider it "consumes" the request. Also I think it is worth mentioning that the "8080 app" doesn't have any route that starts with /second_app, so it cannot conflict with "8081 app". -
Javascript calculate all values from HTML list
I'm developing budget diary web app and have problems with frontend, I have problems with updating budget . Here is my code for Income: script.js var sum =0; $('#li-income-val').each(function() { sum += Number($(this).text()); }); $("#budget-income").text(sum) html code <li id="li-icnome"> <p class="dashboard__income__text"> {{incom.title}} </p> <p id="li-income-val">{{incom.value}}</p> </p> </li> Is there any solutions ? -
need help, i have a problem in django registration (in views)
hi guys i'm new in django .. so i tried to make a registration with a costum user and i'm struggling with errors any help please ? thanks very much for helping me guys views.py from django.shortcuts import render from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth import authenticate,login,logout from django.views.generic import FormView,TemplateView,ListView from .forms import RegisterForm from .models import User # Create your views here. #user-login view def register(request): registred=False if request.method=="POST": user_register=RegisterForm(data=request.POST) if user_register.is_valid(): user=User.save() user.set_password(user.password) user.save() registred=True return HttpResponseRedirect(reverse('index')) else: return HttpResponse('there is a problem') else: return render(request,'register.html',{'registred':registred,'user_register':RegisterForm}) def user_login(request): if request.method=='POST': email=request.POST.get('email') password=request.POST.get('password') user=authenticate(email=email,password=password) if user is not None: return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Account not found") else: return render(request,'login.html') #user-logout view @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) #registration view models.py # accounts.models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) # accounts.models.py class UserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. … -
Python Inheritance and Django
I am just trying inheritance out for the first time in a Django app and I am running into trouble. I have two classes, ProjectDetailView and ProjectDetailViewWithLinks that inherits from ProjectDetailView. I basically want to run a set of functions from the base class (init and then buildContextData). After this I then want to add to the context data using a function called __buildPrevAndNext and then finalise the get function. I have attached some code. The __init seems to work correctly, but when I get to the super().__buildContextData it keeps going wrong and doesn't go into the base class: class ProjectDetailView(View): def __init__(self): self.__contextData = None self.__intPK = None self.__intLangID = None def __buildContextData(self, request, **kwargs): ''' This is used to build the context data that we are going to send to the template. I have done it this way because I want to build two versions of the class. One that has a previous/next project link, but another class that does not. This base class does not have the previous/next link. ''' # Get the primary key of the Project and the corresponding MyProject object self.__intPK = self.kwargs['pk'] project = MyProject.objects.get(pk=self.__intPK) # get the formatted date formatedDate = project.date.strftime("%d-%b-%Y") … -
Django forms templates escape
{% if form.subject.errors %} <ol> {% for error in form.subject.errors %} <li><strong>{{ error|escape }}</strong></li> {% endfor %} </ol> {% endif %} I have taken the above code from a template, a form is passed in under the key 'form' However, i have never encountered |escape before? Is | the or bitwise operator? -
Django Rest Framework: Dynamically Change Nested Object
I'm using a GenericForeignKey and ContentTypes, how can I dynamically change the embedded object in a DRF serializer? So for example: class FooObjectSerializer(serializers.ModelSerializer): """ Represents every foo object """ # 'bar=BarSerializer' if content_type is for Bar model. # 'baz=BazSerializer' if content_type is for Baz model. class Meta: model = models.StoreObject fields = ['id', 'content_type', 'object_id', 'content_object'] -
Display live stream logs in browser like Jenkins console log
views.py def runcommand(command, directory): os.chdir(directory) p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, errors = p.communicate() os.chdir('/Users/pr20121476/NAA/Django_Proj/') return output, errors def stream(request): output, errors = runcommand("/Users/pr20121476/NAA/Django_Proj/app/dashboard/test.sh", "/Users/pr20121476/NAA/Django_Proj/") template = loader.get_template('dashboard/run.html') context = { 'output': output, 'errors': errors } return HttpResponse(template.render(context, request)) run.html {% extends 'dashboard/base.html' %} {% block extrahead %} <script type="text/javascript"> $(function(){ $('a.extendable').click(function(){ $(this).after($('<div class="external-content"></div>').load($(this).attr('href') + ' #content')); return false; }); }); </script> {% endblock extrahead %} {% block content %} <br> <div id="output">{{ output }}</div> <br> <div id="error">{{ errors }}</div> {% endblock %} url.py path('roadrunner/', TemplateView.as_view(template_name='dashboard/roadrunner.html'), name='roadrunner'), path('roadrunner/run', views.stream, name="roadrunner/run"), My requirement is to display output of script in a HTML page as the output log process. In other ways live stream logs like Jenkins console log. Kindly provide some hint or any piece of solution .