Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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/ -
Django save field
im currently trying to save a field (pubpgp) with a none vaule if the user does not provide any information on that (it's optional). But for some reason i'm not able to save the actuall form without providing the information for the field "pubpgp"... how to solve this? def edit_profile(request): if request.method == 'POST': form = UserForm(request.POST, instance=request.user) try: pubpgp = PGPKey.from_blob(request.POST['pubpgp'].rstrip("\r\n"))[0] except: messages.add_message(request, messages.INFO,"PGP-Key is wrong formated.") return render(request, 'edit_profile.html', {'form': form}) if pubpgp.key_algorithm == PubKeyAlgorithm.RSAEncryptOrSign: form.save() messages.add_message(request, messages.INFO, "Profile has been updated successfully.") return redirect(reverse('home')) else: messages.add_message(request, messages.INFO, "PGP-Key is wrong formated.") return render(request, 'edit_profile.html', {'form': form}) else: form = UserForm(instance=request.user) args = {'form': form} return render(request, 'edit_profile.html', args) models.py pubpgp = models.TextField(blank=True, null=True, max_length=3000, unique=True) -
How to display object of two forms in template
I want to display username using {{ object.first_name }}. I am not able to display it. I am also using User in-built module where UserProfile is linked with OneToOneField. profile.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="col-md-6 grid-margin stretch-card"> <div class="card"> <div class="card-body"> <h4 class="card-title">Profile Information - {{ object.first_name }}</h4> <form class="forms-sample" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ u_form|crispy }} {{ p_form|crispy }} <button class="btn btn-success mr-2" type="submit">Update</button> </form> </div> </div> </div> <ul> {% for key, val in object %} <li>{{ key }}: {{ val }}</li> {% endfor %} </ul> {% endblock content %} Views.py def userProfileUpdate(request, pk): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=User.objects.get(id=pk)) p_form = UserProfileForm(request.POST, request.FILES, instance=UserProfile.objects.get(user_id=pk)) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Profile Updated!!!') return redirect('users') else: u_form = UserUpdateForm(instance=User.objects.get(id=pk)) p_form = UserProfileForm(instance=UserProfile.objects.get(user_id=pk)) context ={ 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) UserProfile Model class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) -
Multiple forms generated by for loop in django templates: how to handle them?
[The aim in a nutshell] I am trying to create a view to change the payment status of some lines of a table (Consultations). Each of the unpayed consultations appears as a row on the page generated by a for loop in the template (a pretty convenient solution). Ideally, each line should contain a field to change the value from 0 to whatever_decimal_value and there should be only one button to press once the changes are made. [the problem] I am not sure how to build my view (post) so that every change only affects the relevant consultation. I thought of filtering by form id (where I putted {{c.id}}). I am pretty sure there is a simpler and more elegant solution but, since I am new to web dev, I could not find it. Any thoughts? (be direct, I need to learn) Here is the view: class ComptaDetail(Compta): template = loader.get_template("psy/comptadetail.html") initial = {'payed':0} form_class = AdjustPayed def get(self,request, month): user = request.user adjust_form = self.form_class(initial=self.initial) unpayed = Consultations.objects.filter(owner_id=user.id, payed=0, date__month = month) context = {'unpayed' : unpayed, 'adjust_form' : adjust_form} return HttpResponse(self.template.render(context, request)) def post(self,request, month): adjust_form = self.form_class(request.POST) print(adjust_form) Here is the template: <table class="u-full-width"> <tr> <th>Date</th> <th>Prénom</th> … -
Django list of choices in MultipleChoiceField
I would like to display in a form every existing graph_id that exists in the GraphData model. like so: GRAPHS_CHOICES = (GraphData.objects.all().values_list("graph_id", flat=True).distinct()) class GraphForm(forms.Form): graphs = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=GRAPHS_CHOICES) class GraphData(models.Model): graph_id = models.CharField(max_length=128) date = models.DateField(max_length=128) The problem is that choices expects a tuple, and not a list of id's. How can I supply it with a list anyway? -
How to unit test that django.messages shows a message when duplication creations
Here are the creation view class StorageCreateView(CreateView): model = Storage form_class = StorageForm def post(self, request, **kwargs): request.POST = request.POST.copy() name = request.POST['name'] # branch_id = request.POST['branch'] check_name = Storage.objects.filter(name=name) if check_name.count() != 0: messages.error(request, 'يوجد مخزن بهذا الاسم من قبل') return redirect('erp_system_storage_create') else: pass return super(StorageCreateView, self).post(request, **kwargs) now all that I need is to test this part of showing a message if I try to create a new object with the same name Here is my Test.py part : class StorageTest(TestCase): def create(self, name="only a test"): x = Branch.objects.create(name='testing_for_storage') return Storage.objects.create(name=name, branch=x) def test_creation(self): w = self.create() self.assertTrue(isinstance(w, Storage)) self.assertEqual(w.__str__(), w.name) def test_duplicate_creation(self, name="only a test"): self.create() response = self.client.post(reverse('erp_system_storage_create'), {'name': name}) messages = list(get_messages(response.wsgi_request)) current = messages[0] self.assertEqual(current.message, 'يوجد مخزن بهذا الاسم من قبل') it gives me an error from the line current = messages[0] that says IndexError: list index out of range -
Django: Suggestion for models design
I need help with creating models for my simple Django app. The purpose of the application is to let users (referees) register for matches, then admin will choose 2 users (referees) from the list of registered for given match. Right now my Matches model looks like below: class Match(models.Model): 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 ) What I thought to do is to create new Model named MatchRegister where I will be saving match_id and user_id, something like below: class MatchRegister(models.Model): match_id = models.ForeignKey( Match ) user_id = models.ForeignKey( Users ) And than admin will have list of registered user for given match from witch he will choose two, so I thought to modify my Match model like this (add two new Fields): class Match(models.Model): 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 ) ref_a = models.ForeignKey( Users, … -
"How to fix error in running the web server?"
So I am currently in a virtual environment, and when I type the command line: python manage.py runserver I encounter this problem: Unhandled exception in thread started by .wrapper at 0x000002B3E84C7598> Traceback (most recent call last): File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\core\management\commands\runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\core\management__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\Beatrice\AppData\Local\Programs\Python\Python37\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'reset_migrations' My current Django version 2.0.9. -
the current database router prevents this relation
I am not able to do a reverse relationship lookup for foreign key field. I get below error. model b had foreign key on model a with related_name given. Multiple database is configured. But the foreign key relation is on the same database. I tried to mention database using "using" method. It is not working. My django version is 1.11.15. Any idea why this is happing.? It will be very helpful if any provide pointers. ~/venv/with_line_profiler/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in set(self, instance, value) 224 elif value._state.db is not None and instance._state.db is not None: 225 if not router.allow_relation(value, instance): --> 226 raise ValueError('Cannot assign "%r": the current database router prevents this relation.' % value) 227 228 # If we're setting the value of a OneToOneField to None, we need to clear ValueError: Cannot assign "": the current database router prevents this relation. -
Django ORM: Min('field',filter=...) causes TypeError: can only concatenate list (not "tuple") to list
There is a model Location which can have many Ticket objects (using ForeignKey). The Ticket model has price field which is a DecimalField. Now I have FILTERED QuerySet of Ticket objects and I want to get QuerySet of Location objects and annotate min_price value which is a min price for all Ticket objects from the FILTERED QuerySet. For example: tickets = Ticket.objects.filter(something) locations = Location.objects.all().annotate(min_price=) What I tried: locations_annotated = Location.objects.all().annotate( min_price=Min('tickets__min_price', filter=tickets)) This doesn't work. When I try to get a first element from locations_annotated, debugger returns: TypeError: can only concatenate list (not "tuple") to list Do you know what to do? -
'function' object has no attribute 'objects'
I am trying to get a query set which contains post based on usernames which are stored in model "FollowingProfiles". so models and corresponding views is as follows:- from django.contrib.auth.models import User class Profile(models.Model): Follwers=models.IntegerField(default='0') user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) bio=models.TextField(max_length=120,blank=True) location=models.CharField(max_length=30,blank=True) birth_date=models.DateField(null=True,blank=True) verified=models.BooleanField(default=False) ProfilePic=models.ImageField(upload_to='UserAvatar',blank=True,null=True) def __str__(self): return self.user.username @receiver(post_save,sender=User) def update_user_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class FollowingProfiles(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) ProfileName=models.CharField(max_length=120,blank=True,null=True) def __str__(self): return self.ProfileName class post(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) Picture=models.ImageField(upload_to='PostMedia',blank=True,null=True) DatePosted=models.DateTimeField(default=timezone.now) Content=models.TextField(blank=True,null=True) def __str__(self): return self.Profile.user.username views.py def feed(request): if request.user.is_authenticated: userprofile=FollowingProfiles.objects.filter(Profile__user=request.user) for p in userprofile: postuser=post.objects.filter(Profile__user__username=p.ProfileName) usrpost+=postuser return render(request,'feed/feed.html',{'usrpost':usrpost}) else: return redirect('signup') It produces following error:- function' object has no attribute 'objects' C:\Users\G COMTECH SYSTEM\django-projects\saporaapp\sapora\views.py in feed, line 45 line 45 is postuser=post.objects.filter(Profile__user__username=p.ProfileName) -
Jinja - Arithmetic Operations Using Model Variables
I'm using Django, and I want to convert a variable in my view from m/s to km/h. Currently, my code looks like this: <tr> <td colspan="2">Wind Speed</td> <td>({{weather.wind_speed}} / 1000) * 3600 m/s</td> </tr> What is the correct syntax to do it?