Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test views using RequestFactory() and pytest with Django 2.0+
I am getting familiar testing django views with RequestFactory() I currently have the views below, what is the best way to write the test for? I want to understand how it works, if anybody could show me the proper way the write the tests for these three functions using RequestFactory and mocking the create function. (I would be able to learn for future references) path in the detail function to test is currently crashing for not using the right url apparently. views.py def index(request): universities = University.objects.all() context = {'universities': universities} return render(request, 'core/index.html', context) def detail(request, id): univ = get_object_or_404(University, id=id) context = {'univ':univ} return render(request, 'core/detail.html', context) def create(request): if request.method == "POST": form = UniversityForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = UniversityForm() context = {'form':form} return render(request, 'core/create.html', context) test_views.py def test_list_univeristy(): request = RequestFactory().get('/') resp = index(request) assert resp.status_code == 200 def test_detail_university(): path = reverse('detail', kwargs={'id':1}) request = RequestFactory().get(path) resp = univ_detail(request) assert resp.status_code == 200 def test_create(): pass forms.py class UniversityForm(forms.ModelForm): class Meta: model = University fields = ('name', 'state', 'created', 'is_active' ) urls.py app_name = 'core' urlpatterns = [ path('', views.index, name='index'), path('<int:id>/', views.detail, name='detail'), path('create/', views.create, name='create'), ] -
ForeignKey not appers in the form of browsable api of Django rest framework
i have a conversation model for add topic's and i need to add in diferents categories. So with django mptt i created two models. it seems that in principle it works. But only with the admin dashboard of Django. If I try to create a conversation from the rest browser, the field category does not appear in the form. What will be the reason? Thank you. This is my code: models.py class Conversacion(models.Model): creado_a_las = models.DateTimeField(auto_now_add = True) #Aunque no se la mostraremos al usuario, es una buena práctica tener esto en cuenta actualizado_a_las = models.DateTimeField(auto_now = True) texto = models.CharField(max_length=480) contenido = models.CharField(max_length=90) # Es en realidad el titulo slug = models.SlugField(max_length=500, unique=True) #Para saber los detalles de un aporte en cuestión autor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, related_name= "autor") categoria = models.ForeignKey('Category', on_delete= models.CASCADE,) def __str__(self): return self.contenido class Category(MPTTModel): name = models.CharField(max_length=80, unique=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, default= 1, blank=True, related_name='subcategoria') class MPTTMeta: order_insertion_by = ['name'] class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name serializers.py class ConversacionSerializer(serializers.ModelSerializer): autor = serializers.StringRelatedField(read_only= True) creado_a_las = serializers.SerializerMethodField() actualizado_a_las = serializers.SerializerMethodField() slug = serializers.SlugField(read_only = True) respuesta_cuenta = serializers.SerializerMethodField() usuario_ha_respondido = serializers.SerializerMethodField() class Meta: model = Conversacion fields = '__all__' … -
ModuleNotFoundError: No module named 'my_app' while making migrations
I was trying to make migrations in Django by these commands, python manage.py migrate python manage.py makemigrations python manage.py migrate I have already saved my_app in installed apps[] of settings.py in my project.enter image description here -
In Django Do CreateView and UpdateView have a default template name?
I am following a YouTube tutorial and to the best of my knowledge the video creator did not specify a template name when he put PostUpdateView and PostCreateView in the URL patterns. Do both them views have a default template name as 'your model name'_form.html? Because I have a post_form.html template and I cannot see any URL pattern which is obviously referencing it. -
Laravel vs Django vs Meteor
It comes to a point where I have to choose between frameworks to develop a pretty big intra net at my work place. Previously I have good experience with python in data analysis. However our current work place is using php so I have been learning laravel for the past week. I love the code simplicity, however I want to make sure I choose the correct framework before diving in for a year. Does anyone has experience or reason why would I choose over these 3 popular frameworks? Pros and cons for someone who has switched between these frameworks or things I should know before developing a big web app on top of these frameworks? The new web application will be used accross 50 sites over 1-2k staff every day after we release it next year. Thanks -
How do we import all custom context_processors instead of defining them one by one?
I created a custom context_processor that I wanted to be made available to all templates. So far I only have one custom context processor: context_processor.py def categories_processor(request): categories = Category.objects.all() return {'categories': categories} I added it to template options as so: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['.templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'rss.context_processor.categories_processor', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Now if I were to make like 10 different processors (ex: tags, latest comments, latest blogs, etc) I would have to add them like this: 'OPTIONS': { 'context_processors': [ 'rss.context_processor.categories_processor', 'rss.context_processor.tag_processor', 'rss.context_processor.latest_comments_processor', ... ], This would make it pretty tedious, so I was wondering if there was a way to just import all of the processors within the file? If I try to do: 'rss.context_processor', I would get the following error: Module "rss" does not define a "context_processor" attribute/class -
Break-down/decomposition of Cyberpanel server management package for individual scripts
I want to use some individual scripts within Cyberpanel package, as it opensource and freely available, but I couldn't figure out how and where to begin with and use those scripts individually. Please guide through the process, even if it would requires me to learn something prior to the job, please guide me with that too, would highly appreciate that. -
How to add a variable inside a tag in a django template
django template html에서tag id를 동적으로 할당해주고싶습니다. for exam <p id = '{{~~~}}'>Test</p> Is there no way? -
How to access new data in Djnago UpdateView
I wanted to display in success_message new data, changed in my generic UpdateView. And i dunno how to access those data from form. Everything is like super standard, code look like that: class ProductOneUpdateView(UpdateView): model = ProductOne fields = ['quantity'] success_message = ................ And i want new quantity, changed by user shown in this success_message. Looking forward for yours answers! -
Sending message to Django tutorial chat room from python script
Made the chat room tutorial from the Django channels (here), hosting on a server. Trying to send a message locally with python script. -
migration trouble with unique random default value in model django
I want to add a new field to my already existing model called color. I want it to be unique and also want it to be randomly selected by default. So what I do is: color = models.CharField(max_length=15, default=random_color, unique=True) My random_color looks like this def random_color(): """ Returns: [string] : returns a rgb value in hex string """ while True: generated_color = f'#{random_hex()}{random_hex()}{random_hex()}' if not MyModel.objects.filter(color=generated_color): return generated_color I followed a similar logic to what has been provided here. Now the problem with this approach is that there is no color to begin with to look for. And I also want my migration to add in a bunch of default random color values to my already existing tables. How do I fix this? -
Interactions between HTTP and websocket connections in Django Channels
I have a frontend consumer that handles HTTP requests (webhooks) from django.views.decorators.csrf import csrf_exempt from channels.generic.http import AsyncHttpConsumer from django.http import JsonResponse import json import myapp.models import redis @csrf_exempt class frontEndConsumer(AsyncHttpConsumer): async def http_request(self, request): await self.channel_layer.group_add("link", self.channel_name) await self.channel_layer.group_send("link", { "type": "websocket.reg", "where": "webhook", "message": "test message", }) #channel layer functions async def webhook_reg(self, event): print("WH: message from " + event["where"] + ": " + event["message"] # make response fulfillmentText = "device connected" fulfillmentText = {'fulfillmentText': fulfillmentText} fulfillmentText = json.dumps(fulfillmentText).encode('utf-8') await self.send_response(200, fulfillmentText, headers=[(b"Content-Type", b"text/plain"),]) and I have a backend consumer that handles websocket connections. from channels.generic.websocket import AsyncJsonWebsocketConsumer import redis import myapp.models account = redis.Redis(db=0) class backEndConsumer(AsyncJsonWebsocketConsumer): async def websocket_connect(self, type): await self.channel_layer.group_add("link", self.channel_name) print("channel name: " + self.channel_name) await self.accept() #channel layer functions async def websocket_reg(self, event): print("WS: message from " + event["where"] + ": " + event["message"]) await self.channel_layer.group_send("link", { "type": "webhook.reg", "where": "websocket", "message": "msg from websocket", }) await self.send(event["message"]) I start them in procfile with: web: daphne APbackend.asgi:application --port $PORT --bind 0.0.0.0 I am using django channels to have the front and back talk to each other. In my code, I'm trying to get both sides to send messages to each other. I would … -
How to take parameters from Axios call to a Delete generic view
I'm making a DELETE request through an axios call like this: unfollow(unFollowId) { var payload = { follower_id: this.user.id, followed_id: unFollowId }; axios .delete("http://127.0.0.1:8000/api/tweets/follow/", { headers: { "Content-Type": "application/json" }, data: { payload } }) .then(response => { return response; }) .catch(error => { return error; }); } Views.py The print function is me testing how I can just make sure the parameters are being read properly. class Followers(generics.CreateAPIView, mixins.CreateModelMixin, generics.GenericAPIView): serializer_class = FollowerSerializer def get(self, request, follower_id=None): if follower_id != None: followers = Follower.objects.filter(follower_id=follower_id) else: followers = Follower.objects.all() data = FollowerSerializer(followers, many=True).data return Response(data) def delete(self, request, *args, **kwargs): print(self.queryset()) # unfollow = Follower.objects.filter( # follower_id=follower_id, followed_id=followed_id) # unfollow.delete() return Response(status=status.HTTP_204_NO_CONTENT) def post(self, request): return self.create(request) I've removed the Delete mixin because I'm not sure which I'm supposed to use and how to use it to be able to read parameters. -
Django filtering: model instance vs model pk
I stumbled upon (for me, at least) some rather odd behaviour in Django. I'm not sure if this is supported/allowed behaviour. Suppose I have the following model: class Club name = CharField(....) memberships = models.ManyToManyField(Person, through=ClubMembership, related_name='clubs') def getMembership(self, personID): return ClubMembership.objects.get(club_id=self.id, person_id=personID) Obviously, getMembership returns the associated ClubMembership instance (For now, let's assume we only call this method for persons that are in fact in the club). Now, when calling this method, I found that: club = Club.objects.get(...) person = Person.objects.get(...) membership = club.getMembership(person) and club = Club.objects.get(...) person = Person.objects.get(...) membership = club.getMembership(person.id) are both yielding the correct membership. Is there some magic happening inside the filter/get methods that check if the passend keyword (for person_id) is in fact an integer (pk) or a model instance? If both is valid and allowed, what are the implications? Any differences performance wise? Which would be the preferred method? Ofc I could filter against the entire person model and not just the id, like so: def getMembership(self, person): return ClubMembership.objects.get(club_id=self.id, person=person) But afaik, this would be a lot slower, right? -
Django multimodelform + Inlineformset +updateview
I have a problem with handling the Updateview in django. My design contains 2 models and one Inlineformset. This view will be added with more models and inlineformsets if this works. My createview works fine. But the Updateview gives the attached error error image. Any idea why this is causing. Any better way to handle multiple forms and multipleinlineforms. Forms class CompanyManagementForm(forms.ModelForm): entitynameoptional1=forms.CharField(max_length=200, required=False, label='COMPANY Name (Optional):') entitynameoptional2=forms.CharField(max_length=200, required=False, label='COMPANY Name (Optional):') clientcategory=forms.ModelChoiceField(keyword.objects.filter(keywordtype = 'CLIENT_CATEGORY'), required=False) class Meta: model=EntityList fields =('entitynamepreferred', 'entitynameoptional1', 'entitynameoptional2', 'jurisdiction', 'entitysubtype', 'clientcategory', 'managedbyamicorp', 'origin', 'reasonfortransferin', 'previousserviceprovider') labels ={'entitynamepreferred' : 'COMPANY Name (Preferred):', 'entitynameoptional1':'COMPANY Name (Optional):', 'entitynameoptional2':'COMPANY Name (Optional):', 'jurisdiction':'Jurisdiction', 'entitysubtype': ' Entity Sub-type', 'clientcategory': ' Client category', 'managedbyamicorp': ' Managed by Amicorp', 'origin': 'Origin', 'reasonfortransferin': ' Reason for transfer in', 'previousserviceprovider': ' Previous service provider'} widgets = { 'entitynamepreferred': forms.TextInput(attrs={'class':'form-control'}), } def __init__(self, * args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-4' self.helper.field_class = 'col-lg-8' self.helper.layout = Layout( Fieldset( 'first arg is the legend of the fieldset', 'entitynamepreferred', 'entitynameoptional1', 'entitynameoptional2', 'jurisdiction', 'entitysubtype', 'clientcategory', 'managedbyamicorp', 'origin', 'reasonfortransferin', 'previousserviceprovider' )) class TransactionProfileform(forms.ModelForm): class Meta: model=TransactionProfile fields =('sourceoffund', 'sourcedetaileddescription', 'expectedtransactioninentity1', 'expectedtransactioninentity2', 'expectedtransactioninentity3','transactiondetaileddescription') #entityid, def __init__(self, * args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class … -
Search bar: anchor tag enclosed in list item tags not selectable
I have a search bar in the style of like a google search bar where it gives suggestions based on the user input as you are typing in the text box. It filters through a bunch of items that are contained in an unordered list and runs myFunction() below to parse through the unordered list and display items. The only problem is that when you click the items that are displayed in the search bar, the link redirection doesn't work and I THINK it's because the onMouseButtonUp event doesn't register over the list item (because when I click down and hold the button down, it makes the item disappear if that makes sense)...thoughts? <input style="border-radius: 7px 0px 0px 7px; border-right: 0px; resize: none" id="myInput" onkeyup="myFunction()" name="searchedItem" rows="1" class="form-control" form="searchForm" placeholder="What can we help you find?"> <ul id=myUL> <li><a href="http://127.0.0.1:8000/products/{{ obj.productName }}">{{obj.productName}}</a></li> </ul> <script> var UL = document.getElementById("myUL"); // hilde the list by default UL.style.display = "none"; var searchBox = document.getElementById("myInput"); // show the list when the input receive focus searchBox.addEventListener("focus", function(){ // UL.style.display = "block"; }); // hide the list when the input receive focus searchBox.addEventListener("blur", function(){ UL.style.display = "none"; }); function myFunction() { var input, filter, ul, li, a, … -
Saving form details to Firebase in a django project
I am a beginner in django. I have been facing issue in mapping the variables of the form in my HTML to my python code. I am trying to capture and validate the details provided, and then further process the details to add them into database that is maintained on firebase. Database connectivity is working fine. I have created the firebase object by importing the firebase module already and I am missing on how to provide those details as per the form to make it push to my database. -
django automatic store '' in not null fields
hello my problem is if I don't insert value to not null fields Django must raise error to me, but if I don't send any value to not null fields Django automatic store a '' in not null fields instead of raising errors this is my model class Project(models.Model): title = models.CharField(max_length=100) body = models.TextField() category = models.ForeignKey(Category, models.SET_NULL, null=True) expertises = models.ManyToManyField(Expertise) language = models.CharField(max_length=35) email = models.EmailField() attachments = ArrayField(models.FileField(), null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] and this is code of creating object project = category.project_set.create( title="a title", body='a body text' ) -
Problem reusing serializers with django and drf-yasg
I am using django, django drf and drf-yasg to generate write my BE and generate documentation. I have a model called User and a serializer for a user: class UserSerializer(serializers.ModelSerializer): class Meta: model = users_models.User fields = (users_models.User.first_name.field_name, users_models.User.last_name.field_name,) and I have some method Foo which gets two users. This is what a serializer for the request looks like: class FooRequestSerializer(serializers.ModelSerializer): first_user = UserSerializer(help_text="first user") second_user = UserSerializer(help_text="second user") when I generate a swagger json scheme for this I view the json and the redoc I see that: first_user and second_user have the same ref name ($ref) The description of the second_user and the redoc reads "first user" and not second user. this is because the description is taken from the $ref which has the first user description. I noted that if I make sure the ref names are distinct then the the redoc reads fine since first_user and second_user get their own description. The problem comes since I also want to be able to later use swagger codegen to create Java stubs, so the solution and from what I understand there is a different class for each distinct ref name. Ideally I would see that the call to foo … -
Django refactor FBVs that are very similar?
Refactor FBV's that are very similar? Hi all, I am working with some function based views, and am looking to do some code clean up to eliminate some DRY principles. I have 3 views that look almost identical, just different templates, and queries. login_required def inbox(request): """Display a list of received messages for the current user""" template_name = 'messaging/inbox.html' message_list = Message.objects.inbox_for(request.user) return render(request, template_name, {'message_list': message_list}) login_required def outbox(request): """Display a list of sent messages for the current user""" template_name = 'messaging/outbox.html' message_list = Message.objects.outbox_for(request.user) return render(request, template_name, {'message_list': message_list}) login_required def trash(request): """Display a list of deleted messages for the user""" template_name = 'messaging/trash.html' message_list = Message.objects.trash_for(request.user) return render(request, template_name, {'message_list': message_list}) Is it possible to combine these into one single view, that renders a different template, and a different model query for each message_list context variable? -
Thousand separator with commas and decimal with dots on django template
I don't if it's possible to format some value with that specific way. I know that if I use {{value|intcomma}} I get some like: 1.500 but my problem is that I want something like this: $1,500.50. I don't if I can do it on my template. This is part of my code: {% for subservicio_sel in total_subservicios|servicios_adicionales:servicio_sel %} <li> <div class="row"> <div class="col-6 col-sm-4"> <p>{{subservicio_sel.Servicio_Adicional.Nombre}}</p> </div> <div class="col-6 col-sm-6"> <p>${{subservicio_sel.Servicio_Adicional.Precio|intcomma}}</p> </div> </div> </li> {% endfor %} -
The main application of my website is not viewed when running it
I am not able to launch my website. It is showing the bellow error when running it iPlanetHoster. ModuleNotFoundError at /home/massvnrc/myproject/myproject/myapp/templates/index.html No module named '/myapp' Request Method: GET Request URL: http://www.massiwatech.com/home/massvnrc/myproject/myproject/myapp/templates/index.html Django Version: 1.9.13 Exception Type: ModuleNotFoundError Exception Value: No module named '/myapp' Exception Location: /home/massvnrc/virtualenv/myproject/3.7/lib64/python3.7/importlib/__init__.py in import_module, line 127 Python Executable: /home/massvnrc/virtualenv/myproject/3.7/bin/python3.7_bin Python Version: 3.7.3 Python Path: ['/home/massvnrc/myproject', '/opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts', '/home/massvnrc/virtualenv/myproject/3.7/lib64/python37.zip', '/home/massvnrc/virtualenv/myproject/3.7/lib64/python3.7', '/home/massvnrc/virtualenv/myproject/3.7/lib64/python3.7/lib-dynload', '/opt/alt/python37/lib64/python3.7', '/opt/alt/python37/lib/python3.7', '/home/massvnrc/virtualenv/myproject/3.7/lib/python3.7/site-packages'] Server time: Thu, 23 Jan 2020 18:03:11 +0000 Here are some pictures that are showing where my files are located. enter image description here Can somebody tell me why I am getting this erro -
Django Restframework error: getting Attribute error and Value error
I'm getting the following errors while running my Django 1.11 project with djangorestframework and djangorestframework-extensions: Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/template/base.py", line 903, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [profile] in 'RackToSystem object' Exception while resolving variable 'profile' in template 'customers/rack-detail.template.html'. Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/template/base.py", line 882, in _resolve_lookup current = current[bit] TypeError: 'RackToSystem' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/template/base.py", line 890, in _resolve_lookup current = getattr(current, bit) AttributeError: 'RackToSystem' object has no attribute 'profile' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/template/base.py", line 896, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'profile' Here is my serializers.py code: class RackToSystemSerializer(serializers.ModelSerializer): rack_system = serializers.SerializerMethodField('add_sys_attrs') def add_sys_attrs(self, racktosystem): try: r = racktosystem.system.pk except Exception as nfe: print('System entry NOT FOUND! Check the DB for racktosystem entries that are orphaned.') print(nfe) return {} system = { 'serial': racktosystem.system.serial.number, 'status': racktosystem.system.sys_status, 'connections': racktosystem.system.reconcile_net_connections(), 'position': racktosystem.rack_position, 'reports_path': racktosystem.system.reports_path, 'device_type': 'server', 'hw_violations':[], } try: profiles_to_systems = ProfileToSystem.objects.filter(system__pk = r).select_related() for record in profiles_to_systems: results = record.validate() if results: … -
How to output data from different tables in Django?
I am new to Django and Python, I have a table for clients, and one for trips. I can display the clients on the clients page, and the same for the trips. But on the clients page, I want to show all the trips that are linked to each client. And this is where I hit a wall. This is my models.py from django.db import models from django.core.validators import RegexValidator # Create your models here. class Clientes(models.Model): nome = models.CharField(max_length=30) apelido = models.CharField(max_length=30) morada = models.CharField(max_length=200) tel = models.CharField(max_length=9, validators=[RegexValidator(r'^\d{1,10}$')]) nif = models.CharField(max_length=9, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return "%s %s" % (self.nome, self.apelido) class Meta: verbose_name_plural = "Clientes" class Viagem(models.Model): trip_id = models.CharField(max_length=30) cliente = models.ForeignKey(Clientes, on_delete=models.CASCADE) comp = models.CharField(max_length=30) data = models.DateField() destino = models.CharField(max_length=30) def __str__(self): return self.trip_id class Meta: verbose_name_plural = "Viagens" This is my views.py from django.shortcuts import render from django.http import HttpResponse from .models import Clientes, Viagem # Create your views here. def index(request): ls= Clientes.objects.all() context = {'ls': ls} return render(request, "booking/home.html", context) def cliente(request, id): ls= Clientes.objects.filter(id=id) context = {'ls': ls} return render(request, "booking/cliente.html", context) def trip(request): ls= Viagem.objects.all() context = {'ls': ls} return render(request, "booking/trip.html", context) and this is the table on the … -
Database schema to store previous purchases of an user in a web application
I am devoloping a library management system and would like to design a database schema where I can retreive all the previous loans of a user when queried. I have a table for the information of books and a table for storing the current loans by all users. The schema I have so far is User Deatils- U_ID FNAME EMAIL PASSWORD PHNUMBER BRANCH SEM Book Details BOOK_ID BOOK_NAME AUTHOR PUBLICATION GENRE AVAILABILTY Current Loans U_ID BOOK_ID DATE_BORROWED DATE_RETURN I also want to impose a limit on the number of loans of an user per day. I was thinking about writing a code for it, is it the best approach?