Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, 'ListPostion' object has no attribute 'perms_map'
Reference post: Django Rest Framework use DjangoModelPermissions on ListAPIView I am trying to refer to this post. However, the'ListPostion' object does not have a'perms_map' property. I get an error. I tried a search without knowing the cause, but it did not come out. If anyone knows the answer, please help Below is the code I wrote. view.py from rest_framework import viewsets, permissions, generics from .serializers import PositonListSerializer from .models import PositionList import copy class ListPostion(generics.ListCreateAPIView): permission_classes = [permissions.DjangoObjectPermissions, ] queryset = PositionList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PostionListSerializer def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['GET'] = ['%(app_label)s.view_%(model_name)s'] -
Django 3: Multiple forms in one view
What I'm trying to do is creating an employee where we need to complete the employee profile with Private, Address and Contact form. I have tried 2 things. The first option was creating in de models.py from the app, 3 models: Model for Private class Private(models.Model): GENDER = ( ("Man", "Man"), ("Woman", "Woman"), ) gender = models.CharField("Gender", max_length=15, blank=True, choices=GENDER) initial = models.CharField("Initial", max_length = 15, null=True, blank=True) first_name = models.CharField("First name", max_length=30, blank=True) insertion = models.CharField("Insertion", max_length = 15, null=True, blank=True) last_name = models.CharField("Last name", max_length=30, blank=True, null=True) The second model for Address: class Address(models.Model): street_name = models.CharField("Street name", max_length=80, null=True, blank=True) house_number = models.CharField("House number", max_length=6, null=True, blank=True) Model for Contact class Contact(models.Model): Phone = models.CharField("Phone", max_length=14, null=True, blank=True) email = models.CharField("E-mail", max_length=80, null=True, blank=True) In forms.py from the app I also created 3 forms for each model above. In the Meta class the variable model is linking to each Model. In views.py we have this: def createEmployeePersonal(request): employeeprivate = Private() employeeaddress = Address() employeecontact = Contact() if request.method == "POST": employeeprivate = Private(request.POST) employeeaddress = Address(request.POST) employeecontact = Contact(request.POST, request.FILES) if employeeprivate.is_valid() and employeecontact.is_valid() and employeecontact.is_valid(): employeeprivate.save() employeeaddress.save() employeecontact.save() return redirect("/employees") context = { "employeeprivate": employeeprivate, "employeeaddress": … -
How to map form input to django user model?
I'm a newbie at Django. How could I connect my form to my user model? Essentially, if a user registers for the first time, I want them to go to the form input template but if they're already registered, I want them to go to another page. How may I go about doing this? -
Django URL and Template with inbuilt authentication
I am a Django Beginner, I started by reading WS Vincent..The book created a customUser model in a separate App name USERS. Also, AUTH_USER_MODEL = 'users.CustomUser' has been set up. I have below question related to URLS and Templates . Any help will be appreciated I have been reading that the Default Django login path will go to /accounts/login. However , when I used {% url login %} in template base.html it routed to users/login. That would be coz fo Auth_user_model, but I want to be sure how the above tag would fit in below URL's because there is still no accounts/login URL. If it is getting that from auth.urls package then it only has everything starting with /accounts not /user. I did a packet capture thinking it might be translating to account/login but destination was still users/login. .I hope I was able to explain my query. Please help. urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), # new path('users/', include('django.contrib.auth.urls')),# new path('', TemplateView.as_view(template_name='home.html'),name='home'), # new ] -
Set value in django filter filterset_fields
Hi I'm doing a filter search. In my view, I have implemented filtering, I need to check the permission, and if it is equal to is_partner then filtering by partnerId__user__id should be = user_id, else is my entered value. How can I implement this? I can't figure out how to access the filter and set its value. my code models class Partner(models.Model): user = models.OneToOneField(AbstractUser, on_delete=models.CASCADE, primary_key=True, related_name='user') objects = BaseManager() class Meta: db_table = "userPartner" permissions = ( ("is_partner", "Partner user"), ) class Event(models.Model): title = models.CharField( _('title'), max_length=255, ) description = models.TextField( _('description'), ) enabled = models.BooleanField( _('enabled or disabled') ) partnerId = models.ForeignKey(Partner, on_delete=models.CASCADE, default=0) view class SerarchParnterEvents(generics.ListAPIView): queryset = Event.objects.filter(enabled=True) permission_classes = [ProjectPermission.IsPartner | ProjectPermission.IsAdmin] serializer_class = EventSerializer filter_backends = [filters.SearchFilter, DjangoFilterBackend] search_fields = ['title', 'description'] filterset_fields = ['partnerId__user__id'] def check_permissions(self, request): if request.user.has_perm('User.is_partner'): ??????? serializer class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('id', 'title', 'description', 'enabled', 'partnerId' ) extra_kwargs = {"partnerId": {'read_only': True}, } -
TypeError: HomeConsumer() takes no arguments
I am working on channels using django, and i am having 2 different consumers for 2 differrent web pages , but while executing the web page i am getting type error for consumer This is consumer.py file from channels.consumer import AsyncConsumer import asyncio class ChatConsumer(AsyncConsumer): async def websocket_connect(self,event): await self.send( { 'type':'websocket.accept', } ) print("connected",event) async def websocket_receive(self,event): print("received",event) async def websocket_disconnect(self,event): print("disconnected",event) class HomeConsumer(AsyncConsumer): async def websocket_connect(self,event): await self.send( { 'type':'websocket.accept', } ) print("connected",event) async def websocket_receive(self,event): print("received",event) async def websocket_disconnect(self,event): print("disconnected",event) This is my routing.py file import os from channels.routing import ProtocolTypeRouter,URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application from django.urls import re_path from .consumer import ChatConsumer,HomeConsumer from django.conf.urls import url os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^profile/(?P<username>[\w.@+-]+)",ChatConsumer), url("profile",HomeConsumer) ] ) ) ) }) THis is my websocket javascript: var loc = window.location console.log(loc) var endpoint = "ws://" + loc.host + loc.pathname var socket = new WebSocket(endpoint) socket.onmessage = function(e) { console.log("message", e) } socket.onopen = function(e) { console.log("open", e) } socket.onclose = function(e) { console.log("close", e) } socket.onerror = function(e) { console.log("error", e) } This is my urls.py file: from django.contrib import admin from django.urls import path,include from … -
use manytomany field in both the models Django
I have two models named Profile and Controversy. My requirement is many people can be involved in a controversy and a single person can have multiple Controversies. With that said, I feel like I should a ManyToMany field in both the models but I'm guessing that violates ManyToMany fields documentation as it should be used in only model. my models are as follows : class Profile(models.model): name = models.CharField(max_length=200) Controversy = models.ManyToManyField(Controversy) # As one person can have multiple controveries class Controversy(models.Model): year = models.Datefield() other_people_involved = models.ManytoManyField(profile) # As multiple people can be involved in a controversy description = models.TextField() This obviously will throw error. I'm not able to understand as to how to tackle such a scenario -
Django - 'QuerySet' object has no attribute 'get_upvotes_count'
I am a beginner at Django and I am trying to build an app to manage games. It is possible for registered visitors to rate the game. Furthermore you can comment the game and this comment can be rated as well. But only once. The difficult thing for me is the independent evaluation of comments and articles. Furthermore, the "Queryset" error message occurs when I create a game. I already tried to initialize the attribute "comment" in the views with "None". Did not work. How do I get the app running ? Here is my views.py: from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 # Create your views here. from django.shortcuts import redirect, render from django.urls import reverse_lazy from django.views.generic import CreateView, DetailView, ListView from .forms import GameForm, CommentForm from .models import Game, Comment class GameListView(ListView): model = Game context_object_name = 'all_the_games' template_name = 'games-list.html' class GameDetailView(DetailView): model = Game context_object_name = 'that_one_game' template_name = 'game-detail.html' class GameCreateView(CreateView): model = Game form_class = GameForm template_name = 'game-create.html' success_url = reverse_lazy('game-list') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def game_list(request): context = {'all_the_games': Game.objects.all()} return render(request, 'game-list.html', context) def game_detail(request, **kwargs): game_id = kwargs['pk'] game = Game.objects.get(id=game_id) comment = … -
How to view items in database selected by user in a django app?
I have a model orders that stores users orders at a restaurant. I want to create a view that allows me to show every item available in the database on the home page in a grid. Then when a user clicks on any of the items it should take them to a new page with more info on the item. How would I set logic for the view, to know what item the user clicked? -
AttributeError: module 'enum' has no attribute 'IntFlag' from Azure
I have a Django project running on Azure, and I encountered this issue with the enum module and I have tried everything from here(Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?) The problem is that I don't have the issue locally, I only see the issue on Azure. Therefore, I cannot just uninstall it locally. I have tried to uninstall it in the Azure terminal, but it showed that the module was not found. I have also tried to install aenum instead of enum by adding it to requirements.txt, still didn't work. Can someone please advise me on how to fix this issue? Here is a screenshot of the error Here is the link to the source code -
Django: Many To Many Field allow fields to be added if it is in another field
I'm experimenting with Django and I'm trying to figure out Many to Many Relationships. Let's say I have certain model named "Facility", similarly I created another model named "Hotels" which contains fields 'facility' and 'featured_facility' both are in Many To Many relationship with "Facility". I want to add featured_facility only if it is available in 'facility' fields how can I do that? Here is my models code class Facility(models.Model): name = models.CharField( max_length=100, validators=[validate_facility_name], unique=True, ) description = models.CharField(max_length=100, validators=[validate_facility_description]) can_be_featured = models.BooleanField(default=False) similarly Hotel model is class Hotels(models.Model): hotel_name = models.CharField( max_length=20, unique=True, validators=[validate_hotel_name] facility = models.ManyToManyField( Facility, related_name='hotel_facility', blank=True, ) featured_facility = models.ManyToManyField( Facility, related_name='featured_hotel_facility', blank=True, ) class Meta: default_permissions = () verbose_name = 'Hotel' verbose_name_plural = 'Hotels' def __str__(self): return self.hotel_name Now I want to add 'featured_facility' only if it is available in 'facility' no new featured facility from Facility can be added in 'featured_facility' how can I do that? -
Django Error: ImproperlyConfigured / define the environment variable / call settings.configure()
I have the following model: class my_model(models.Model): item_id = models.IntegerField(max_length=100) item_array = ArrayField(models.FloatField()) When I try: df = pd.read_pickle('df.pkl') db = my_model() for item in df.columns: db.item_id = item db.item_array = df[item] db.save() I get the following error: ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. What could I do to fix this? -
Creating an array field in a Django Model
Hey guys I'm creating a basic social media app and I'm trying to create an array field that can hold a list of followers that a user is following and is later used to print out the posts of all the users followers. How do I create an array or list with Django that will allow me to save multiple fields for multiple follows? Right now, I have it as an Integer field. Thanks! class User(AbstractUser): pass follows = models.CharField(max_length=64, default=0) followers = models.IntegerField(max_length=64, default=0) -
Git merge conflict in django project
I am working on a django project. I have two branches, master and alpha. I am trying to merge the two branches. My alpha branch is the finished product. The two branches are dramatically different. I keep getting a merge conflict. I deleted the database in the master. I want the database in the alpha to be the main one. can anyone help me. How do I successfully merge them. -
request.POST parameters are missing
Hello I am trying to pass some values from my signup form to a django view but for some reason the values are missing. My view.py : @csrf_exempt def signup(request): if request.method =='POST': for key, value in request.POST.lists(): print(" DEBUG %s %s" % (key, value)) print(request.POST['name'],email=request.POST['email']) return render(request, 'front_app/login.html') My register.html : <form class="form" method="post" action="{% url 'signup' %}" name="submitForm"> {% csrf_token %} <input type="text" class="name" placeholder="Name" id="name" required> <input type="email" class="email" placeholder="Email" id="email" required> <div> <input type="password" class="password" placeholder="Password (8 characters minimum)" id="password" minlength="8" required> </div> <input type="submit" class="submit" value="Register" > </form> and my urls.py : urlpatterns = [ # other not related urls path('signup', views.signup, name='signup'), ] My problem is that when the views.signup function is running it is missing all three values that I am trying to send : name, email and password. It is a POST request (and not GET) but the only values in the QueryDict are the "encoding" and "csrfmiddlewaretoken" values. Any help is appreciated! -
Django user password hash, oracle db, and java
im developing and ecommerce site on django for a Sushi Restaurant, and i have to create a CRUD for users in java and edit info from the database in oracle, the database are generated with django, so my questions are. how can i deal with the django hash for password? change password from the java crud app would be nice, if can i disable the hash from django would be nice to, its just a institute project, so doesn't matter the security. -
HTML not rendering properly
I'm trying to render an HTML in my django project on the basis of data that I'm receiving from the backend but can't understand on how to do it. If somebody can help me out that would be super awesome. Thanks Here is the structure of the data that I have { "structure":"linear", "layout":[ { "structure":"Rubber_Duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "Quack", "Quack! Quack!" ] }, "custom_behaviour":"", "is_duck":true }, { "structure":"Model_duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "MuteQuack", "No Quack!" ] }, "custom_behaviour":"", "is_duck":true }, { "structure":"grid", "layout":[ { "structure":"Mallord_Duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "Quack", "Quack! Quack!" ] }, "custom_behaviour":"", "is_duck":true }, { "structure":"Rubber_Duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "Quack", "Quack! Quack!" ] }, "custom_behaviour":"", "is_duck":true }, { "structure":"Rubber_Duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "Quack", "Quack! Quack!" ] }, "custom_behaviour":"", "is_duck":true }, { "structure":"Rubber_Duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "Quack", "Quack! Quack!" ] }, "custom_behaviour":"", "is_duck":true } ] }, { "structure":"linear", "layout":[ { "structure":"Model_duck", "default_behaviour":{ "fly":[ "FlywithWings", " I am Flying!! " ], "quack":[ "MuteQuack", "No Quack!" ] }, "custom_behaviour":"", … -
Can I serve static files (css, html, etc.) from a different server in Django
So I'm trying to serve templates, images, css and other static files from a Web Server (frontend) running Apache into an App Server (backend) running Django, the Django app is already proven to work locally so I splited static files and push them into the Web server and the .py files into the App Server, so far I've seen that I need to use mod_wsgi package from Apache and then run $ python manage.py collectstatic So it makes a copy of those static files into the App Server. But the problem comes when changing the urls of every template. Also I saw this other solution but I'm not sure if I implement that solution I still need to do the mod_wsgi thing. Can someone please help me out here please? Or give me some advice on how to do it? Thanks -
AWS Elastic Beanstalk : Deploying Django application Failed
I've been trying to deploy my Django backend for my react application on EB but I can running into an error when I try deploying.I'm not sure how to pull up more details from the log, but I have also attached by requirements.txt file below the error results. 2020-11-22 23:44:27 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2020-11-22 23:44:30 ERROR [Instance: i-0da4be9088c225a28] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2020-11-22 23:44:31 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2020-11-22 23:45:33 ERROR Create environment operation is complete, but with errors. For more information, see troubleshooting documentation. asgiref==3.3.1 attrs==20.3.0 awsebcli==3.19.2 bcrypt==3.2.0 blessed==1.17.11 boto3==1.16.23 botocore==1.19.23 cached-property==1.5.2 cement==2.8.2 certifi==2020.11.8 cffi==1.14.3 chardet==3.0.4 colorama==0.4.3 cryptography==3.2.1 Django==3.1.3 django-cors-headers==3.5.0 django-environ==0.4.5 django-storages==1.10.1 djangorestframework==3.12.2 docker==4.3.1 docker-compose==1.25.5 dockerpty==0.4.1 docopt==0.6.2 environ==1.0 future==0.16.0 idna==2.10 jmespath==0.10.0 jsonschema==3.2.0 mysql-connector-python==2.0.4 mysqlclient==2.0.1 paramiko==2.7.2 pathspec==0.5.9 Pillow==8.0.1 pycparser==2.20 PyMySQL==0.10.1 PyNaCl==1.4.0 pyrsistent==0.17.3 python-dateutil==2.8.1 pytz==2020.4 PyYAML==5.3.1 requests==2.24.0 s3transfer==0.3.3 semantic-version==2.5.0 six==1.15.0 sqlparse==0.4.1 termcolor==1.1.0 texttable==1.6.3 urllib3==1.25.11 wcwidth==0.1.9 websocket-client==0.57.0 -
How to pass 2 parameters in for loop in django templates
i want to pass 2 parameters in for loop in my template {% for x, y in text %} <p>{{ x }}</p><h1>{{ y }}</h1> {% endfor %} my views: text = [("e", "w"), ("1", "2")] return render(request, "my_template.html", {"text": text}) this isn't even loop and it does absolute nothing what I need to write in the template or in "text" to make this work? -
Django Post Deployment Issues - Scripts and Models
Hi it's my first time deploying a Django app. I'm using PythonAnywhere to host and learn more. I am aware that deployment requires additional steps and code changes versus dev and believe I have taken these steps researching the documentation and other issues on Stack Overflow. After separating out javascript from the html, migrating the models and collecting the static files I'm having a major issue with the style of the index file not inheriting the base layout as well as being running the javascript. Additionally drop downfields that are reading from models are not working. Note all other pages are inheriting the base file but are not linking to models either for dropdowns. I've reviewed the models and they are in place and populated. Likely I am missing something with the base layout file and the models. Greatly appreciate if someone can point me in the right direction. Layout.html (base layout file) <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'app/content/bootstrap.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'app/content/site.css' %}" /> <script src="{% static 'app/scripts/modernizr-2.6.2.js' %}"></script> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" /> </head> … -
Restricting Signal Notifications in a Django Project to specific Attribute in Model
I have added a notification everytime a user submits a Like button to a post, the owner of the liked post receives a notification. I have set Value options for each Like button to be Like or Unlike so now I am trying to restrict the notification to be sent only if the Value of the like clicked is Like only. So, now in the Like Model I have added signal and a condition that if the Like.value== Like the signal activates but for some reason it is not working and I am not sure why. My question is: How do I set the notification signal to be sent only when the Like.value== Like? Here is the post models.py: class Post(models.Model): title = models.CharField(max_length=100, unique=True) likes = models.ManyToManyField(User, related_name='liked', blank=True) Here is the like models.py: LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): # To know Who liked user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post}-{self.user}-{self.value}" def user_liked_post(sender, instance, *args, **kwargs): if Like.value=='Like': like = instance post = like.post sender = like.user notify = Notification(post=post, sender=sender, user=post.author, notification_type=1) notify.save() else: None def user_unlike_post(sender, … -
how to set a timer or schedule non-periodical task in Django > 3.0 and DRF
Im new to async programming and new Django's docs aren't really specific what should and should not be done so here is my question. How to set some kind of a timer in Django (or django-programatically in server) after which some Django code will be run. To visualize this I will present an example: Student has 10 minutes to write a test. Student starts a test (enters some view). Student can post his test results within those 10 minutes but if he crosses the 10 minute barrier, the test should stop and such event should be saved in database. This sounds like an async job but I don't know the good practise for coding that. If it can be done synchornousily it would be much better. To clarify - I'm using Django REST framework and the student is on a mobile client. (setting a timer in mobile app is not an option due to security reasons). I know about Celery but it seems like an overkill when Django already has async. I will add that there will be several tousand student tests running at the same time so performance is important. Can anyone help me or point me to a … -
How to add two Field Instances in a Django Model into a variable?
Good day! I'm trying to understand if there is a proper way of adding name_first & name_last Fields in the Customer Model into name_full Field. The name_full Field will be used as ftring renurn value for the Model. Relation with the Order Model via Foreign Key. class Customer(models.Model): name_first = models.CharField(max_length=30, null=False, blank=False) name_last = models.CharField(max_length=30, null=False, blank=False) # name_full = ... name_first+name_last def __str__(self): return self.name_full I've tried looking for similar question and there is a slight chance of not knowing how to ask a proper question) Cheers! -
Store a matrix in Django
I have the following matrix: item_1 item_2 item_3 item_1 1 0 0 item_2 0 2 0 item_3 0 0 3 What is the best way to store this matrix into django, so that in the future I can retrieve an entire column (being able to see the ID of each row), and use it to perform some calculations in a view? Obs: This matrix is going to have thousands of columns and rows.