Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch error after saving form in Django
I am getting NoReverse at / def createOrder(request, pk): Here is my code: https://github.com/alauddinmondal/crm1/blob/master/accounts/views.py after saving the form and redirecting to homepage -
Random function in twig template show **Could not parse the remainder: '()' from 'random()**
I am developing a site in django web framework. I am aiming to use random function provided by twig in my template. But, I it shows an error showing Could not parse the remainder: '()' from 'random()'. My code:- <a href="javascript:void(0);" data-id="justrandom-{{ random() }} actualid-{{ comment.id }}"> I don't know what I did wrong. Obvioulsy, if I don't use random(), template is working fine. Do I have to import something to use random function in template? Here, is the twig documentation where they used random function. Twig -
Access variables without re-loading them between management commands in Django
We are building an AI enabled web application that uses huge memory models that ideally should be loaded only once in memory as global variables. These variables are to be used by different management commands which run as individual processes and make use of the Django framework. And of course, the runserver command too accesses these global variables. These models are loaded inside a single module commons but since we are spawning different processes, let us assume two for now - runserver and process_tasks, these models are essentially loaded twice in memory via the commons module. Is there a way to load these models centrally and share the variables between independently spawned processes. I'm aware of the multiprocessing module in python and the Manager API, but can't figure out a way for incorporating it with the current scenario. Is there a way to run a standalone python process that holds these variables and be able to access them from multiple other processes? -
Serialize multiple objects without ModelViewSet
I have models and serializer and views with rest framework However I want to make view not by viewsets.ModelViewSet by my original one get_by but in ModelViewSet serializer could be set easily serializer_class = MyTextSerializer serializer.py class MyTextSerializer(serializers.ModelSerializer): my_status = serializers.SerializerMethodField() class Meta: model = MyText fields = ('id','text','created_at','pub_date') def get_my_status(self,obj): res = ["mystatus"] return res normal ModelViewSet view but I don't want to use this now. class MyTextViewSet(viewsets.ModelViewSet): queryset = MyText.objects.all().order_by('created_at') serializer_class = MyTextSerializer ## serializer works here. pagination_class = StandardResultsSetPagination in views.py I wanto use this. @api_view(['POST', 'GET']) def get_by(request): ts = MyTexts.objects.all().order_by('id')[0:10] serializer = MyTextSerializer(ts[0]) ## it works, but I want to serialize multiple items `ts` return Response(serializer.data) However I have no idea how to pass the multiple queryset to Serializer as ModelViewSet dose. Does anyone help?? -
Django is not setting REMOTE_USER
I am trying to get the information about the user who is accessing the website for user authentication and for some other purpose also. After looking at official documentation of Django I got this article but still when I am trying to access request.META["REMOTE_USER"] I am getting the error because no key exists. After some tweaks when I tried again I was getting the username of my PC even if I tried to access my website from another PC on from the same network. I am using Django's lightweight server for testing, hosted on my PC and trying and access the website from another PC on the same network. Please help and try to resolve this issue. -
Periodic database backup in kubernetes?
How to setup periodic database backup in kubernetes? I have deployed a postgres database as StatefulSet in kubernetes and mounted a PersistantVolume to store data. Now to get periodic backup for the mounted volume, I found three options, Setup a CronJob in kubernetes and execute pg_dump and upload to the storage location. I have already using celery in my project. So now add a new task to backup postgres data and upload to the storage location. VolumeSnapshots. This looks more kubernetes way. But I couldn't find a way to automate this periodically. Which is the recommended way to take periodic volume backup in kubernetes? -
Within Django - in the HTML Files the {% 'commands %} arent working
im trying to follow a Python Course to build a Dashboard in Django - currently im have no more ideas left, why i cant use the {& load/include ..%} commands within my HTML files? Any ideas? Am I missing some packages or something else? Please be gentle im a newjoiner. I also added two pictrues of the problem. enter image description here Second one: enter image description here -
Error in virtual Environment while running Django Project
When I tried running my Django project in a virtual environment, it gave the following error after running python3 manage.py runserver. OS: Elementary OS Python: 3.6.9 Django: 3x Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/contrib/admin/checks.py", line 76, in check_dependencies for engine in engines.all(): File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/template/utils.py", line 90, in all return [self[alias] for alias in self] File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/template/utils.py", line 90, in <listcomp> return [self[alias] for alias in self] File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/template/utils.py", line 81, in __getitem__ engine = engine_cls(params) File "/home/aditya/PycharmProjects/Sortal/venv/lib/python3.6/site-packages/django/template/backends/django.py", line 27, in __init__ self.engine = Engine(self.dirs, self.app_dirs, **options) TypeError: __init__() got an unexpected keyword argument 'context_videoplaybackprocessors' As seen from above this has nothing to do with the files from my … -
ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding'
I was trying to run-server and I got this error. I was building an app for inventory management this is the screenshot of error python version 3.8.1 django version 3.0.4 -
Deploying Django with Apache not working (Bad linux distro?)
I have tried every methods, every tutorial, and read every question related here, I just can't seem to get it working, I restarted my PC once and got it barely serving the DocumentRoot but merely as an index of the main site, and I think the problem is actually with my os not the httpd.conf, I would really appreciate the help. OS: Manjaro Linux Apache2 version: 2.4.41 (Custom installed not the default one) Django version: 3.0.3 Python version: 19.0.0 And here is my httpd.conf file: # All the default modules + mod_wsgi are above here Listen 127.0.0.1:5000 ServerName 127.0.0.1 <VirtualHost *:5000> ServerAlias localhost ServerAdmin webmaster@example.com WSGIDaemonProcess myproj python-home=/usr/bin/python3.6 python-path=/home/myusername/server/myproj/ processes=2 threads=15 display-name=myproj WSGIProcessGroup myproj WSGIScriptAlias / /home/myusername/server/myproj/myproj/wsgi.py process-group=myproj <Directory /home/myusername/server/myproj/myproj/> <Files wsgi.py> Require all granted </Files> </Directory> DocumentRoot /home/myusername/server/myproj <Directory /home/myusername/server/myproj/renderer/templates> <IfVersion < 2.4> Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.4> Options Indexes FollowSymLinks Includes ExecCGI Require all granted </IfVersion> </Directory> <Directory /home/myusername/server/myproj/> <IfVersion < 2.4> Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.4> Options Indexes FollowSymLinks Includes ExecCGI Require all granted </IfVersion> </Directory> </VirtualHost> -
how to upload an image in comments?
i have a small form in my blog detail view and it has a name,last name,email and an image field. the first three work fine but when i add the imagefield in the form, the form wont save from the page but it works from admin page. this is my views.py: def campaign_detail_view(request, id): template_name = 'gngo/campaign-detail.html' campaign = get_object_or_404(Campaign, id = id) comments = CampaignForm.objects.filter(campaign=campaign).order_by('-id') form = FormCamp(request.POST) if request.method == 'POST': if form.is_valid(): name = request.POST.get('name') last = request.POST.get('last') email = request.POST.get('email') comment = CampaignForm.objects.create(campaign=campaign,name=name,last=last,email=email) comment.save() return redirect('campaign-detail',id=id) else: form = FormCamp() context = { 'campaign':campaign, 'comments':comments, 'form':form, } context["object"] = Campaign.objects.get(id = id) return render(request, template_name, context) and this is my comment model: class CampaignForm(models.Model): campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE) name = models.CharField(max_length=100) last = models.CharField(max_length=100) email = models.EmailField() this is a non user form, so everyone can fill it. please help me understand how to add the ability to upload an image in this form oh and this the form: class FormCamp(forms.ModelForm): class Meta: model = CampaignForm fields = ('name','last','email',) THANKS ALOT FOR THE ANSWERS AND SUPPORTS -
Which approach is better, Using Union all view on multiple tables or dumping all data to a database table from multiple tables?
I am working on an ERP System which has tables like Sales, Purchase, Receipt and Payment. I need to union all data from these tables to get ledger balance. I have come up with two different solutions to this problem. Create a table TransactionData and while inserting rows in Sales, Purchase, Receipt and Payment, insert related data to TransactionData as well, so that I will have a table which has all the transactions in it and I can query them whenever required. As per my logic, This approach is performance efficient as inserting data to two tables at a time will be faster as compared to the second approach listed below. Insert data only to respective tables i.e. Sales, Purchase, Receipt and Payment, and create a view using union all to have all the transactions at one place, Which can be queried later whenever required. As per my logic, This approach will be slower as each time a query being run over this view, DBMS will have to first union all the results from multiple tables and then resolve the query on it. Further, I am using Django as backend, So, If available, I am also looking for a better … -
Decrement the value defends on the current date in django
How to decrement the SLA value defends on the current date and auto-update in PostgreSQL everyday with the current value, until the SLA value reach to 1? -
How to auto update data in django?
I am trying to build eCommerce application in Django. In each product I have three label tags which are is_new, is_hot, is_promo. is_new will be True when a product will create, I have done it. But the system needs to automatically make is_new to False when a product is older than 7 days. I have added created_date field in Product model. How could I auto update is_new to False? Any hints? is_hot will be True when a product will most sold. Actually the first two product will be hot. And when other product goes hot then previous hot products will be automatically False. How to do it? Hints? is_promo will be True when I will add discount to a product. And it will be False when I will remove the discount. Any hints? -
Django how to convert the older format url to the newer format path
I am using ajax to create a GET request to django, and I want to convert the older format url to the newer format path. This line works url(r'^setComplete/$', views.setComplete, name='setcomplete'), While this line fails with 404(http://127.0.0.1:8000/project/setComplete?item_id=1) Not found path('set_complete/<int:item_id>',views.setComplete, name='setcomplete'), Here is the Ajax code $.ajax( { type:"GET", url: "/project/setComplete", data:{ item_id: itemid }, success : function(data) { console.info("Success",data); }, error : function(e) { console.info("Error",e); }, done : function(e) { console.info("DONE",e); } }) Here is a simple view just for testing def setComplete(request): return HttpResponse("Success!") # Sending an success response -
Adding password value to serialized data during update and setting new permission (drf)
I am using django rest framework and DjangoModelPermissions, I have serialized the default User Model to get information about the users and their permissions and also admin can change the permission as per requirement from the front-end (some JavaScript) or make some user a superuser. The problem is when admin tries to do a PUT statement with new data it fails. In User model password is the mandatory required field. I have got user's authentication token(which does not work) and i have not serialized password from users model and i don't want to. I tried to append serialize data before saving to add one more field "password" by getting the values using user.objects.get(username=data_from_serializer_data).password but i am not able to add an extra field(password field) to serializer data. What may be the way to achieve my goals? how can i add password value in serializer data(at back-end) and then send complete data for update. Also i read somewhere that serializer.data is a property which can not be edited. If true what else will i have to do to complete my task? Thanks -
Django CBV. I need to fill 3 dropdowns with different models in the same template on Django?
I have a doubt, there is a way through the CBV to have results from several querysets of different models for a single template. Do I need to fill 3 dropdowns in the same template? How to do this? Thanks -
how to get other ModelField Value on my actual form? DJANGO
Thanks for your time: i want to set Validation Error with data that is already written in other modelclass. Models.py class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person') birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.user) class Pets(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE) nome = models.CharField(max_length=150) custo = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.SmallIntegerField() def __str__(self): return '%s - %s' % (self.pessoa, self.nome) Forms.py: class PetForm3(forms.ModelForm): #SELECIONAR FORM PELO FORMS.PY field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'ANDORINHA') ] nome = forms.CharField(max_length=100) custo = forms.DecimalField(max_digits=7, decimal_places=2) tipo = forms.ChoiceField(choices=field_choices) class Meta: prefix = 'pet' model = Pets fields = ['nome', 'custo', 'tipo'] def clean_tipo(self): data = self.cleaned_data.get("tipo") data_nome = self.cleaned_data.get("pessoa") slug = slugify(data_nome) if slug.startswith('a'): data == 2 raise forms.ValidationError('nomes com A nao podem ter gatos') return data i got these two models and the Pets is a ManytoOne to People i'd like to take attributes of People like birthday and cpf in the clean_method of PetForm3. and like to get the ''pessoa'' field from Pets on the clean method either. i'm able to achieve something like that with request.user in views.py but i'd like to get it in clean_method at forms.py -
Circular importing error using wagtail-generic-chooser
I am using wagtails wagtail-generic-chooser to create customChoosers for my data models and it is working great whenever I am referencing other modelAdmin models. However, I have come across a situation where I have a Lexis model with a field that has a FK link to itself. The idea is to have a Lexis term, and then there can be related lexis terms connected to it. It works fine with a normal FieldPanel but this isn't a very good UI experience when there are hundreds of lexis terms. Accordingly, I wanted to create a custom LexisChooser for this field. However, the issue I've run into is according to the documentation in order to create a functional widget, I am required to create both a view and adminChooser that references the model the ChooserPanel is connected to. https://github.com/wagtail/wagtail-generic-chooser#chooser-widgets-model-based This makes sense, however, when I then try to import my LexisChooser into my Lexis model to use the LexisChooser as a widget, I get the error below. ImportError: cannot import name 'Lexis' from 'lexis.models' I realize this is due to a circular import error issue because I have subclasses that are importing the Lexis Class in order to build the LexisChooser widget … -
Django channels testing failed
I am trying to make a chat application on django using channels 2. I am following the tutorial here : https://channels.readthedocs.io/en/latest/tutorial/part_4.html , though am following it on windows while the code is actually meant for linux. I am getting this error while testing : (hackathon) C:\Users\PARAM BHATT\PycharmProjects\ChatHead\chatsite>py manage.py test chat.tests Creating test database for alias 'default'... Destroying old test database for alias 'default'... System check identified no issues (0 silenced). DevTools listening on ws://127.0.0.1:52430/devtools/browser/6d5d1d7f-3df0-4583-bc1d-992f7803932e EETraceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\spawn.py", line 109, in spawn_main fd = msvcrt.open_osfhandle(new_handle, os.O_RDONLY) OSError: [Errno 9] Bad file descriptor Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\spawn.py", line 107, in spawn_main new_handle = reduction.duplicate(pipe_handle, File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\reduction.py", line 79, in duplicate return _winapi.DuplicateHandle( OSError: [WinError 6] The handle is invalid ====================================================================== ERROR: test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room (chat.tests.ChatTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\PARAM BHATT\PycharmProjects\ChatHead\hackathon\lib\site-packages\django\test\testcases.py", line 267, in __call__ self._pre_setup() File "C:\Users\PARAM BHATT\PycharmProjects\ChatHead\hackathon\lib\site-packages\channels\testing\live.py", line 52, in _pre_setup self._server_process.start() File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\process.py", line 121, in start self._popen = self._Popen(self) File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\context.py", line 224, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\context.py", line 326, in _Popen return Popen(process_obj) File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__ … -
Django - Annotate multiple fields from a Subquery
I'm working on a Django project on which i have a queryset of a 'A' objects ( A.objects.all() ), and i need to annotate multiple fields from a 'B' objects' Subquery. The problem is that the annotate method can only deal with one field type per parameter (DecimalField, CharField, etc.), so, in order to annotate multiple fields, i must use something like: A.objects.all().annotate(b_id =Subquery(B_queryset.values('id')[:1], b_name =Subquery(B_queryset.values('name')[:1], b_other_field =Subquery(B_queryset.values('other_field')[:1], ... ) Which is very inefficient, as it creates a new subquery/subselect on the final SQL for each field i want to annotate. I would like to use the same Subselect with multiple fields on it's values() params, and annotate them all on A's queryset. I'd like to use something like this: b_subquery = Subquery(B_queryset.values('id', 'name', 'other_field', ...)[:1]) A.objects.all().annotate(b=b_subquery) But when i try to do that (and access the first element A.objects.all().annotate(b=b_subquery)[0]) it raises an exception: {FieldError}Expression contains mixed types. You must set output_field. And if i set Subquery(B_quer...[:1], output_field=ForeignKey(B, models.DO_NOTHING)), i get a DB exception: {ProgrammingError}subquery must return only one column In a nutshell, the whole problem is that i have multiple Bs that "belongs" to a A, so i need to use Subquery to, for every A in A.objects.all(), pick … -
Keep same web page after POST request on iOS devices (Django sending 204 status response)
My Django project has a number of buttons on the web page that do POST requests to the main view.py which in turn handles the action and returns a 204 No content response. The results of the action show up asynchronously later on the web page (at the time the response is generated there's nothing new to show). On any non-iOS based browser the 204 response works fine and the web page remains in the browser, as expected from RFC 7231. Unfortunately all iOS based browsers I've tried (Safari, Firefox, Chrome) navigate to a blank page after the POST, which is not what I want (see this question). Apparently this is a long standing bug in WebKit. Is there any way to achieve the same thing across all browsers? ie. Click button, POST, web page stays as is, change appears later. I've looked at this but no sure it's really what I'm after. Changing the response code is possible but I don't see a viable alternative that doesn't navigate away from the current page. My current hacky fix is to reload the whole page for an iOS device, but this moves the page if the user had scrolled down earlier … -
django.core.exceptions.FieldError: Cannot resolve keyword 'ModelList' into field. Choices are: borrows, dept_list, dept_list_id, email_ad
i am a beginner of Djanog, i am experiencing a problem of django.core.exceptions.FieldError: Cannot resolve keyword 'ModelList' into field. Choices are: borrows, dept_list, dept_list_id,..... i have try to remove the files on migrations folder excuted python manage.py makemigrations and migrate ,and reload nginx, restart uwsgi, issue will appear again after the server run normally for a moment. the issue is not heppen immediately after the server up, also , i have try to rename the field name, but this is not helpful for solving the issue. could you please help chech where is wrong, where does the issue come from ? ''' class pc_list(models.Model): host_name=models.CharField(max_length=64, unique=True) service_tag=models.CharField(max_length=45,unique=True) #hosttype_list=models.ForeignKey('hosttype_list', to_field='id',default=1, on_delete=None) ModelList=models.ForeignKey('ModelList',to_field='id',on_delete=None) host_spec=models.CharField(max_length=45) price=models.FloatField(default=0) receive_date=models.DateField(auto_now_add =False, default='2018-01-01') user_list = models.ForeignKey('user_list', to_field='id', on_delete=None, default=180) seat_no = models.IntegerField(default=14000) PcStatus=models.ForeignKey('PcStatus', to_field='id', on_delete=None, default=2) studio = models.CharField(max_length=45, default='-') site_list=models.ForeignKey('site_list', to_field='id', on_delete=None) asset_code = models.IntegerField(default=1) remark=models.TextField(max_length=200, default='-') mac=models.CharField(max_length=15, default='-') class Meta: ordering = ('host_name',) def __str__(self): return self.host_name class PcStatus(models.Model): statusname=models.CharField(max_length=45,default='--') def str(self): return self.statusname class ModelList(models.Model): name = models.CharField(max_length=40) hosttype_list = models.ForeignKey('hosttype_list',to_field='id',on_delete=False) def __str__(self): return self.name class Meta: ordering = ('name',) view as below class pcDataView(FeedDataView): token = pc_listTable.token def get_queryset(self): siteid = self.request.session.get('current_site') hosttypeid=self.request.session.get('hosttype_id') if hosttypeid ==0: return super(pcDataView, self).get_queryset().filter(site_list_id=siteid , ModelList__hosttype_list_id__in=(1,2,3,12)).exclude(PcStatus_id=4) else: return … -
Manage Parent Child Category in django
Django Models I'm working on a e-commerce website where I need to assign child category to a parent category like if when add product admin will select parent category then its relevant child category should come to select in I tried doing like this but didn't able to find solution class MainCategory(models.Model): # name = models.CharField(max_length=50) # date_created = models.DateTimeField(auto_now_add=True) # def __str__(self): # return self.name # class SubCategory(models.Model): # perentcategory = models.OneToOneField(MainCategory, on_delete=models.CASCADE, primary_key=True) # name = models.CharField(max_length=50) # date_created = models.DateTimeField(auto_now_add=True) # def __str__(self): # return self.name # class Items(models.Model): # main = models.ForeignKey(SubCategory, on_delete=models.CASCADE) # name = models.CharField(max_length=255) Please Share How I can do that -
How can I solve this error [missing 1 required positional argument: 'request']?
When I tried using a session on DetailView class in the Django project, I have an error and it does not work because of the missing a request object. in that case, how should I do? Would you mind telling me how should I solve this problem? Thank you in advance. the error code TypeError at /detail/41/ check_session() missing 1 required positional argument: 'request' views.py class DetailView(LoginRequiredMixin, generic.DetailView): model = sampleDB template_name = 'detail.html' def check_session(self, request): if not 'history' in request.session: request.session['history'] = {'user': self.request.user, 'id': self.kwargs['pk']} def get_context_data(self, **kwargs): self.check_session() context = super().get_context_data(**kwargs) return context Development environment Python: 3.7.5 Django: 2.2.2