Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin custom queryset for a custom action
I am a bit lost on how to perform a specific queryset in django admin. Below are my models. class People(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=35) phone_number = models.CharField(null=True, blank=True, max_length=15) def __str__(self): return self.first_name class Meta: verbose_name_plural = 'People' class Group_and_message(models.Model): name = models.CharField(max_length=30, null=True) people = models.ManyToManyField(Person) message_body = models.TextField(max_length=140) updated = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return self.name In Admin, I have created a custom action. def send_message(modeladmin, request,queryset): pass My question is to be able, when selecting a "group_and_message" object in the admin dashboard via the checkbox, be able to retrieve "id" and "phone_number" of the selected object so i can use it to perform "send_message" custom action. Below is the equivalent of basic of a few queryset steps that showcase what i am trying to achieve(just for illustration purpose) g = Group_and_message.objects.last() #self instead of last is what i want; g1 = g.people.all() g2 = g1.values_list("id","phone_number"); g3 = dict(g2) The result gives me the "id" and "phone number". Any help would be much appreciated. -
How to add an image to a jinja html page
I'm just learning the basics of django and jinja. I've extended my header file and now I want to add an image to the page, but I don't know the jinja syntax for doing that. Please assist. {% extends "media/header.html" %} {% block content %} This is where I would like to insert my image. {% endblock %} -
TinyMCE HTMLField not works with extra defined language
I have this in models.py: from django.db import models from tinymce import models as tinymce_models class Article(models.Model): title = models.CharField(max_length=50) content = tinymce_models.HTMLField(verbose_name=_('Content')) Also, I determined english, russian and uzbek languages in settings.py using EXTRA_LANG_INFO. TinyMCE configurations in settings.py: TINYMCE_DEFAULT_CONFIG = { 'theme': "advanced", 'relative_urls': False, # default value 'width': '100%', 'height': 300, 'plugins': "table,spellchecker,paste,searchreplace" } TinyMCE works good for already defined languages in package (for english and russian in my case), works fine in admin (https://imgur.com/a/AgaH2de) But its not displays text field in admin for extra added language (https://imgur.com/a/k3LQl7y) How to fix this problem? Thanks. -
Find average after annotation subtract without aggregate Django-rest-framework
I have a lot of querys that want to return in a single request, I have a query with an aggregate and when we concat the queryset with this function and try to serialize the function returns an error: ['All items in the ConversasAPIViewSet querylist attribute should contain a queryset key'] Is there any kind of solution for this problem? APIViewSet: class ConversasAPIViewSet(ObjectMultipleModelAPIViewSet): kpiDTO = KpiDTO(6) json = Conversas.objects.values('nome' ).annotate(deltaTime = (Max('data') - Min('data')) ).aggregate(tempoMedioTotal=Avg('deltaTime')) qtdUsuariosMes, qtdMensagensMes, fraseIntentEntity, tempoMedioTotal = kpiDTO.retornaDTO() querylist = [ {'queryset': qtdMensagensMes, 'serializer_class': QuantidadeMensagensMesSerializer, 'label': 'qtdMensagensMes'}, {'queryset': qtdUsuariosMes, 'serializer_class': QuantidadeUsuariosMesSerializer,'label': 'qtdUsuariosMes' }, {'queryset': fraseIntentEntity, 'serializer_class': EntidadeIntencaoSerializer, 'label': 'fraseIntentEntity'}, {'queryset': json , 'serializer_class': TempoMedioSerializer, 'label': 'tempoMedio'} ] Serializer: class TempoMedioSerializer(serializers.Serializer): tempoMedioTotal = serializers.CharField() -
How to create online SQL compiler using Django [on hold]
I'm trying to create an online compiler of SQL where one can practice SQL queries. I'm using Django for this purpose can some tell me what should be the flow of the wbsite . I need some clear idea of what to use and how to use(in implementation) Thanks in advance -
How can Import a csv file into a Django project?
I can't import a csv file into my Django project. I have a code that is already working that basically takes a csv file and output spendings on different categories (using pandas). I'm learning Django right now and I'm trying to include that code into my project. But everytime I try to run in it says 'No module named StatementOCTRev'. I'm not sure if it's a directory thing or a pandasXdjango thing. I tried different approaches but none of them work. That led to an ugly code. So I apologize. Anyway here is my view.py: from django.shortcuts import render, get_object_or_404 from .models import Post from .budget import Categorize, Spending import numpy as np import pandas as pd import csv import mysite.StatementOCTRev from import_export import resources #import # Create your views here. def home(request): posts = Post.objects return render(request, 'mysite/home.html', {'posts':posts}) def post(request,post_id): ################################ coffeelist = ["WING", "COSTA", "CAFFEINE", "PASSO", "LA FELICE", "GULLUOGLU", "CARIBOU", "ARK COFFEE"] restlist = ["TALABAT", "SOLO", "MELENZANE", "PIZZA", "HARDEES", "HARDEE'S", "MCDONALDS", "GULF ROYAL", "SARAY", "Carriage"] gaslist = ["KNPC", "OULA", "ALFA"] read = pd.read_csv('StatementOCTRev.csv', encoding="ISO-8859-1") # Read CSV # create a new dataframe df = pd.DataFrame(columns=["Date", "Reference", "Debit", "Credit", "Balance"]) df['Date'] = read.iloc[:, 0] df['Reference'] = read.iloc[:, 1] … -
How to fix "config for 'compressor' " error in Django
I'm following the Django-SHOP tutorial https://django-shop.readthedocs.io/en/latest/tutorial/intro.html#tutorial-populate-database-fixtures. After successfully declaration of demo implementation I tried running my app. I got the traceback: [2018-12-28 18:21:07,071 exception] ERROR: Internal Server Error: / Traceback (most recent call last): File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 109, in get_exception_response response = callback(request, **dict(param_dict, exception=exception)) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/views/defaults.py", line 45, in page_not_found body = template.render(context, request) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/backends/django.py", line 66, in render return self.template.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 207, in render return self._render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", … -
Django - Store the language of user in database
I am able to change the language of the user with built-in function of django path('i18n/', include('django.conf.urls.i18n')), In order to send email to user translated in his language, I want to know the activated language of the user. How can I save the language of the in db? Is there another way to know the language? This is the session: from django.utils import translation request.session[translation.LANGUAGE_SESSION_KEY] -
How can I not display 'Id:' when I render my form? (same as 'ParentClass ptr:')
I have made a form (Formset actually) with modelformset_factory. I display it with <form method="post" action=""> {% csrf_token %} {{ player_formset.management_form }} {% for player_form in player_formset %} {% for field in player_form %} {{ field.label_tag }} {{ field }} {% endfor %} <br> {% endfor %} <input type="submit" value="Aggiungi"> </form> When it render automatically adds a field with the write 'Human ptr:' (because my model, Player, is a subclass of Human... if I use directly Human he shows me 'Id:', the title is just to generalize the problem). How can I delete this write? I tried: 1) to use in html file the tag {% forloop.last %} but actually the last field is 'Delete:' checkbox (if I use can_delete=False it works, but I need it) 2) change label in PlayerForm(ModelForm) Meta, but seem not working for this field. It's strange that instead works widgets = {'human_ptr': Input(attrs={})} but it affects the {{ field }} not the {{ field.label_tag }} If can be useful I add all the parts of the involved code: forms.py from skeleton.models import Player from django.forms import ModelForm from django.forms.widgets import Input class PlayerForm(ModelForm): class Meta: model = Player fields = ['first_name', 'last_name', 'jersey_number'] labels = … -
In a Postgresql database where a seller has many products and products have many sellers, where should price(s) get stored?
Using django and python, I am building a web app that tracks prices. The user is a manufacturer and will want reports. Each of their products has a recommended price. Each product could have more than one seller, and each seller could have more than one product. My question is, where do I store the prices, especially the seller's price? Right now I have my database schema so the product table stores the recommended price and the seller's price, and that means one single product is repeated a lot of times. Is there a better way to do this? -
Django url template tags adding absolute filepath
I am having a problem where my {% url %} django template tag is adding the filepath to the web address in production. This is not replicated on my local development machine. With urls.py setup such that: url("^about_us/$", views.about_us, name="about_us"), In production, I am getting the link www.mysite.com/home/username/myapp/about_us instead of www.mysite.com/about_us I have looked at this similar issue and it does not help with my specific application: Django url tag adds filepath My django project is hosted on A2 (shared) hosting using apache, wsgi, and passenger. My .htaccess file look the following: # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/user/myapp" PassengerBaseURI "/" PassengerPython "/home/user/virtualenv/myapp/2.7/bin/python2.7" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END My passenger_wsgi.py file looks like the following: import myapp.wsgi SCRIPT_NAME = '/home/user/myapp' #SCRIPT_NAME = '/' class PassengerPathInfoFix(object): """ Sets PATH_INFO from REQUEST_URI because Passenger doesn't provide it. """ def __init__(self, app): self.app = app def __call__(self, environ, start_response): from urlparse import unquote environ['SCRIPT_NAME'] = SCRIPT_NAME request_uri = unquote(environ['REQUEST_URI']) script_name = unquote(environ.get('SCRIPT_NAME', '')) offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0 environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0] return self.app(environ, start_response) application = myapp.wsgi.application application = PassengerPathInfoFix(application) I feel like something is off in one of these files. How can I … -
how to post a dummy json response to the server without adding it to database using Django rest framework
im trying to figure out is there any way to create post json response to the server without adding it to database tried using APIView but that didnt work with my code async def index(request): async with aiohttp.ClientSession() as client: data=await(email_sending(client)) print(data) await client.post('http://127.0.0.1:8000/acc/signup/',data=data) return web.Response(text="OK") async def email_sending(client): async with client.get('http://www.mocky.io/v2/5c23aef12f00003300049691') as resp: resp=await(resp.json()) totp = pyotp.TOTP('base32secret3232') otp=totp.now() smtp.sendmail("you@gmail.com",resp['email'], otp) # await asyncio.sleep(30) sucess=asyncio.create_task(email_verification(otp,client)) # await sucess return resp async def email_verification(otp,client): async with client.get('http://127.0.0.1:8000/connect/hello/') as v_otp: v_otp=await(v_otp.json()) print(v_otp) here you can see from the following code it gets email adress and username from another server as json and then sends an otp to that email and now i want to use django rest framework to create a temporary json response for that email_verification step so that i can verify that email (but as of now the code just prints the response) here is what i have tried earier @api_view(['GET', 'POST']) def hello_world(request): if request.method == 'POST': return Response({"message": "Got some data!", "data": request.data}) return Response({"message": "Hello, world!"}) # class hello_world(APIView): # def post(self, request): # # if request.method==POST: # otp=request.data # return Response({'otp':otp}) but couldnt figure out how to make it happen -
Django not redirecting when sing up [on hold]
I'm creating a sign-up form but it is not redirecting after sign up, please help enter image description here -
Django: model does not render fields correctly in Admin
I've a model that I know is recording correctly the values in DataBase, but it is not showing them correctly in Admin Panel. I know it's saving this fields correctly because: 1.- I can Query the model in Shell and see the values correctly. 2.- I'm using this model's fields to create another model, and this other model saves correctly and SHOWs correctly it's fields in Admin Panel. What could be wrong? Shell: >>> SizeQuantity.objects.get(pk=9) <SizeQuantity: variante_125 por cantidad_200> >>> SizeQuantity.objects.get(pk=9).size 'variante_125' >>> SizeQuantity.objects.get(pk=9).quantity 'cantidad_200' What I see in AdminPanel: This is my other model that uses values from SizeQuantiy: I was expecting to render the Size and Quantity fields like this for my SizeQuantity model: from .models import Cart, SizeQuantity # Register your models here. admin.site.register(Cart) admin.site.register(SizeQuantity) -
Django query get objects that are not in other object
I know that probably it is dummy question, but I cannot find answer to it. I want to get list of all Matches that are not in MacthRegister object, but I cannot do it. Could you please help me achieve it? Below my two classes class Match(models.Model): """Model representing Match object""" match_number = models.CharField( max_length=10 ) home_team = models.ForeignKey( Team, on_delete=models.SET_NULL, null=True, related_name='home_team' ) away_team = models.ForeignKey( Team, on_delete=models.SET_NULL, null=True, related_name='away_team' ) match_category = models.ForeignKey( MatchCategory, on_delete=models.SET_NULL, null=True ) date_time = models.DateTimeField( default=timezone.now ) notes = models.TextField( max_length=1000, blank=True ) last_update = models.DateTimeField( auto_now=timezone.now ) class MatchRegister(models.Model): match = models.ForeignKey( Match, on_delete=models.SET_NULL, null=True ) -
How to use django-erd 1.0?
Is there any documentation of django-erd 1.0 ? I can not find one. I need to generate my models ERD. I am using Django 2.0 -
Not able to exit from virtual environment python django.(Tried Deactivate,source deactivate and exit nothing worked)
I am trying to exit from the virtual environment which I have created for running my Django application. Now I am not able to exit from it. I have tried all the command deactivate, source deactivate, exit (just to make sure anything works in my case). I have even deleted all the virtual environments as I am not able to exit. But still, I am not able to exit from it. Environment: Python 3.7.2 ( not anaconda) Thanks in advance. below is the error message: deactivate : The term 'deactivate' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + deactivate + ~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (deactivate:String) [], CommandNotFoundE xception + FullyQualifiedErrorId : CommandNotFoundException -
How to make currency form in Django
I'm very newby in Django apps, I wanna make currencry form in Django template. So example when I'm input 5000 in the form, the form automatically change to 5,000.00. I'm using DecimalField in my model. The ouput that I wanna make like the picture I'm upload it -
Django unique_together from abstract model field
Suppose I have an Abstract Model: class SoftDelete(models.Model): _active = models.NullBooleanField(default=True) class Meta: abstract = True And a model that inerhits from this abstract model: class SomeModel(AbstractModel): some_field = models.IntegerField() class Meta: unique_together = ('_active', 'some_field') Here I've constrained some_field with the _active field by using unique_together, which is used by a soft-delete feature I have. That works and all but, every model I have an unique constraint now needs to apply _active into the uniqueness since when deleted it's not really deleted, only _active = None. My question is, since all my models will inerhit from SoftDelete is there an efficient way of applying _active to all models that have in their Metas an unique_together constraint? Instead of manually adding it and maybe forget of it. I was hoping to add something like bellow to abstract's Meta class: For unique_together in child_unique_together: unique_together.append('_active') -
how to make values from input form not disappear after page is refreshed using django
I have a html table of variable dimensions in which every cell is <input type = "number"> After the user has filled every cell and pressed submit, a result of some calculation should be printed in a h2 tag. As predicted every time user presses submit the content that was written inside the table is deleted. Is it possible to somewhat negate that so that after the user has pressed submit he gets the result outputted but his input in the table stays where it was? This is html of the template where all of this is happening: {% extends "base.html" %} {% block content %} <h2> Dimensions: {{ f_number }} X {{ s_number }} </h2> <form method = "post" action="/calculated/">{% csrf_token %} <table style = "border: 1px solid black;" border = 1> {% for i in range_first %} <tr> {% for j in range_second %} <td> <input type = "number" name = "{{ i }}{{ j }}"> </td> {% endfor %} </tr> {% endfor %} </table> <input type = "Submit" value = "Calculate" name = "calc"> {% if result %} <h2> The result is: {{ result }}. </h2> {% endif %} </form> {% endblock content %} -
PolyDrawTool in embed plot is not shown in Django
I am trying to insert a PolyDraw in a embed plot (using Django). Here is the code (from here): from bokeh.plotting import figure, output_file, show from bokeh.models import PolyDrawTool def test(request): p = figure(x_range=(0, 10), y_range=(0, 10), width=400, height=400, title='Poly Draw Tool') p1 = p.patches([[2, 5, 8]], [[2, 8, 2]], line_width=0, alpha=0.4) l1 = p.multi_line([[1, 9]], [[5, 5]], line_width=5, alpha=0.4, color='red') draw_tool_p1 = PolyDrawTool(renderers=[p1]) draw_tool_l1 = PolyDrawTool(renderers=[l1]) p.add_tools(draw_tool_p1, draw_tool_l1) p.toolbar.active_drag = draw_tool_p1 script, div = components(p) content = {'script':script,'div':div} return render(request,'test.html',content) At the moment it is running in a local server, but it does not give any errors, it shows only a blank page. Thanks a lot in advance. -
Supress warnings of 4xx response code of views in Django
I am trying to suppress some specific warning message of a view that's returning a 404 when the object is not found. I have tried: with warnings.catch_warnings(): return bad_request_response(_('City not found.'), resp_status=HTTP_404_NOT_FOUND) But django seems to go around that and shows in the logs: WARNING Not Found: /auth/cities/ I am working with Django 1.11. Any hint is welcome -
Can I make a serializer fail silently?
I have to serializer a list of email addresses. If one of them contains a wrong character (in one case, it was a ":" at the end of the address) my serializer throws an error, rejects serializing the whole set of addresses and returns a HTTP 400. Is there a way to "pop" the faulty email address from the list but still serialize the remaining correct addresses? View: @action(detail=False, methods=['post']) def match(self, request): serializer = FriendFinderSerializer(data=request.data, many=True) if serializer.is_valid(): contacts = serializer.validated_data matched, unmatched = self.match_contacts(contacts) serialized_matched = FriendFinderSerializer(matched, many=True) serialized_unmatched = FriendFinderSerializer(unmatched, many=True) data = { 'matched': serialized_matched.data, 'unmatched': serialized_unmatched.data, } return Response(data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer: class FriendFinderSerializer(serializers.Serializer): id = serializers.IntegerField(required=False) image = serializers.ImageField(required=False) record_id = serializers.CharField() phone_numbers = serializers.ListField(child=serializers.CharField(), required=False) email_addresses = serializers.ListField(child=serializers.EmailField(), required=False) relationship_id = serializers.CharField(required=False) relationship_status = serializers.CharField(required=False) -
NameError: name 'Recipe' is not defined
I'm trying to run a script in django using the following command: python manage.py shell < recipes/launch_bundle.py The script is as follows: from recipes.models import Recipe def create_bundle(recipe_id): rec = Recipe.objects.get(pk=recipe_id) print('done') create_bundle(1) Notice the first line- the model Recipe should be imported. When run, i get the error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 92, in handle exec(sys.stdin.read()) File "<string>", line 7, in <module> File "<string>", line 4, in create_bundle NameError: name 'Recipe' is not defined I am confused because I clearly import Recipe, and further because i can launch a shell with python manage.py shell, then copy paste the code and it works fine. What is the issue here? Why does my code run fine in the shell, but not when called as a script? Please note i have researched other questions, but they all seem to say: you havent imported the model, or something similar -
Ignore http:localhost from ajax url
Im using django channels for implementing instant messaging app in my project.The message box does not take up th entire screen ,so im trying to implement it using ajax.The problem im facing is that in my url field in the ajax is prepending with http://locahost .I dont want thi since imm using ASGI and django channels with ws:// I have tried prepending the url with a "/" var wsStart = 'ws://'; if (loc.protocol == 'https:'){ wsStart ='wss://'; } var endpoint = wsStart + loc.host; $.ajax({ type: 'POST', url:"/"+endpoint+"/messages/"+username+"/", data: { 'username': username, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function (res, status) { console.log("RESOPONSE",res); }, error: function (res) { console.log(res.status); } }); I want the url to be ws://localhost:8000/messages/ what i get now is http://localhost:8000/ws://localhost:8000/messages/mohitharshan123/