Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: store a json string as data attribute in Django template
In Django i am passing a json string to template and want to store it as a data attribute in an html tag and later use that json string in Jquery Like def sampleView(request) data = {"param1": 1, "param2": "testing"} json_string = json.dumps(data,indent=4,default=str) return render(request, 'my_home.html', dict(data=json_string)) Now i want to store it as a data attribute in html my_home.html .... <div id="test" data-sample={{ json_string }}>.... .... and in jquery i want to convert back to json. How can i do it -
Dajngo Session Data Not Being Stored
I am trying to store some session data using Django and Angular2. I noticed something strange, or do not understand. I was stuck on this for a while on my project. Instead, I tried to test a simple example to understand what's happening. Finally, I was able to store the session data when I made the requests using POSTMAN, and the sessionId was recognized. However when I made the request through my Angular app, the session data saving was successful but it was unable to access the saved session data on the next request. I also noticed that when done with Angular, a new session is created on every request. So it's not recognizing the session and creating a new session each time. Any ideas on what might be causing this? Thank you for your help. Django Views class TestSaveSessionView(APIView): authentication_classes = (TokenAuthentication,) def post(self, request): # set new data request.session['user_id'] = 20 request.session['team'] = 'Barcelona' return Response("Session Data Saved") class TestAccessSessionView(APIView): authentication_classes = (TokenAuthentication,) def post(self, request): response = "" print("USER ID", request.session.get('user_id')) if request.session.get('user_id'): user_id = request.session.get('user_id') response += "User Id : {0} <br>".format(user_id) if request.session.get('team'): team = request.session.get('team') response += "Team : {0} <br>".format(team) if not response: … -
Django Rest Framework and Heroku - Error 401
I just deployed my website on Heroku, an integral part of the functionality of the site is to receive post requests from another website of mine. I'm using DRF's TokenAuthentication for my authentication. In my local environment everything works perfectly, but the same cannot be said for the live website. Whenever I send a POST request I receive a 401 error, the new token is added to the request's header and the data is exactly the same as the data used in the local environment. Any help would be gladly appreciated. views.py class PetCreateView(CreateAPIView): serializer_class = PetSerializer permission_classes = [IsAuthenticated, ] def perform_create(self, serializer): if Breed.objects.filter(user_id=self.request.POST.get('breed_name', None)).exists(): pass else: Breed.objects.create( breed_name=self.request.POST.get('breed_name', None), size=self.request.POST.get('size', None), temperament=self.request.POST.get('temperament', None), energy=self.request.POST.get('energy', None), hypoallergenic=self.request.POST.get('hypoallergenic', None)) breed = Breed.objects.get(breed_name=self.request.POST.get('breed_name', None)) # Assigns a groomer the created Pet groomer = assign_groomer(breed) serializer.save(groomer=groomer, breed=breed) SpaReport.objects.create(breed=breed, groomer=groomer) settings.py ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'bootstrap3', 'captcha', 'django_celery_beat', 'django_celery_results', 'mathfilters', 'storages', 'account', 'sales', 'scrty', 'analytics' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pettracker.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR, ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', … -
Django custom manager breaks create method
I implemented a custom Manager which overrides get_queryset and returns custom QuerySet. Like: class CustomQuerySet(models.Queryset): def custom_method(self): return self.filter(foo='bar') class CustomManager(models.Manager): def get_queryset(self): return CustomQuerySet(self.model, using=self._db) and I'm using it as: objects = CustomManager() but running tests in which I'm using factories, it doesn't set value for created = (DateTimeField with auto_now_add=True) field during .create() method. Anyone encountered a similar problem? -
How to insert NULL value in existing object's field using Django
I am trying to insert the null value in some fields of a predefined object. my models.py: class myCustomeUser(AbstractUser): username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) def __str__(self): return self.username class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) def __str__(self): return self.name class Employee(models.Model): user = models.ForeignKey(myCustomeUser, null=True, blank=True, on_delete=models.CASCADE) industry = models.ForeignKey(Industry, null=True, blank=True, on_delete=models.CASCADE) i_id = models.IntegerField(unique=True) name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) rank = models.CharField(max_length=20, blank=False, null=True) employee_varified = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return self.name I have already created an Employee object. Now I am trying to delete some of that existing Employee object's field in views.py by the following code: Identified_employee = Employee.objects.get(i_id=pk) if request.method == 'POST': Identified_employee.industry = NULL Identified_employee.i_id = NULL Identified_employee.rank = NULL Identified_employee.save() But it says error in terminal like: Traceback (most recent call last): File "G:\Python\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "G:\Python\lib\site-packages\djongo\sql2mongo\query.py", line 783, in __init__ self._query = self.parse() File "G:\Python\lib\site-packages\djongo\sql2mongo\query.py", line 868, in parse raise exe from e djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: INSERT INTO "app_prevjob" … -
Adding Swagger Docs to Django Without Django REST FRAMEWORK
I am working on a Django project and there's requirement to build the APIs without using the Django rest-framework library. I'm having a hard time figuring out a work around as more available libraries are already tied to the Django rest-framework pip library. Can someone point me to an example, library or resource for self documented APIs using swagger docs that supports at least Python 3.7 -
Supporting search queries in Django Rest Framework
Im currently trying to allow users to search my database from the client side and return the response to them. I'm a little confused on where in the view I need to support the search query, or if the way I'm going about it is even correct. I've done some research already and found out about the SearchFilter from DRF but unsure how to incorporate it into my code. Here is my views for the resource i'm trying to search: class Recipes(ViewSet): def list(self, request): recipes = Recipe.objects.all() user = self.request.query_params.get('user', None) if user is not None: recipes = recipes.filter(author = user) serializer = RecipeSerializer(recipes, many=True, context={'request': request}) return Response(serializer.data) def retrieve(self, request, pk=None): try: recipe = Recipe.objects.get(pk=pk) serializer = RecipeSerializer(recipe, context={'request': request}) return Response(serializer.data) except Exception as ex: return HttpResponseServerError(ex) Based on my research I've found that I can use: serializer_class = RecipeSerializer queryset = Recipe.objects.all() filter_backends = (SearchFilter,) filter_fields = ('title', 'ingredients') in some way but i'm not exactly sure how. Any guidance is appreciated -
How to use on_delete CASCADE for some objects and ondelete DO_NOTHING for others in djando models
I have a Django model that refers to itself as below: parent = models.ForeignKey('self', ...) I need to act in some situations as on_delete=models.CASCADE and in other situations as on_delete=models.DO_NOTHING. How can I do that? -
how to use relationship in django
i have a Order and OrderProductDetail model class Order(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) is_paid = models.BooleanField(verbose_name='پرداخت شده / نشده') payment_date = models.DateTimeField(blank=True, null=True, verbose_name='تاریخ پرداخت') class OrderProductDetail(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, verbose_name='سبد خرید') product = models.ForeignKey(Mahsoolat, on_delete=models.CASCADE, verbose_name='محصول') price = models.IntegerField(verbose_name='قیمت محصول') created_at = models.DateTimeField(verbose_name="تاریخ ثبت", default=datetime.datetime.now()) in views.py (orders have two items) orders = Order.objects.filter(owner_id=request.user.id, is_paid=True) at each item of orders contain several items now how can i retrieve all items of orders that exist in OrderProductDetail model -
How to return HTML in another page with AJAX?
So I created a form. In this form, I make GET requests to the server to search for particular users. The view responsible for using the query words returns a template as follows. html with the form <a href="{% url 'logout'}">Logout</a> <p>Welcome</p> <form id="search" method="GET" action="{% url 'results' %}" placeholder= "Choose a friend" autocomplete="off"> {{form}} <input type="submit" value="search" name="search"> </form> <a href="{% url 'liked' %}"> View Liked Songs</a> {% endblock %} `views to handle data passed into the form` def results(request): if request.method == "GET": search_query = request.GET.get("username") searched_user = UserProfile.objects.filter( user__username__contains=search_query ) return render( request, "searched_results.html", { "searched_user":searched_user }) else: return HttpResponse("Search returned nothing") This is where the issue is. Now I have two HTML files. One ought to display data returned in the results view but I want it displayed only wheni click a button in the other HTML file. This is what I mean; I have this HTML file which is rendered when the results/ route is used. {% extends "base.html" %} {% block spotify %} {%if searched_user %} {% for each_searched_user in searched_user %} <br/>{% for liked_songs in each_searched_user.liked_songs.all %}{{liked_songs}}<br/> {% endfor %} {% endfor %} {% endif %} {% endblock %} But I want the … -
UpdateView with form_class removes named submit input from POST
I want to get the input that was clicked by the user. The submit goes to an UpdateView with a ModelForm. I've added the name attribute to the submit inputs but when I do if 'approve' in self.request.POST: in get_context_data() it's False. I overridden def post() and it appears. Is there a way to do it without overriding def post()?. FYI, I've omitted some code that was just bloat and not relevant to the issue. Apologies if there's something in there that doesn't make sense. models.py class Definition(DefinitionInfo): SEV3 = 'info' SEV2 = 'warning' SEV1 = 'danger' sup_sevs = ( ('', 'Please select'), ('info', 'Sev3'), ('warning', 'Sev2'), ('danger', 'Sev1'), ) title = models.CharField(max_length=255) description = models.TextField(null=True, blank=True) resolution = models.TextField(null=True, blank=True) sup_sev = models.CharField(max_length=7, choices=sup_sevs, null=False, blank=False) forms.py class DefinitionForm(forms.ModelForm): class Meta: model = Definition fields = ['title', 'sup_sev', 'description', 'resolution'] widgets = { 'description': forms.HiddenInput(), 'resolution': forms.HiddenInput(), } views.py class DefinitionUpdate(LoginRequiredMixin, UpdateView): model = Definition context_object_name = 'definition' form_class = DefinitionForm template_name_suffix = '_form' success_url = reverse_lazy('definitions:index') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.method == 'POST': print(f'Post data: {self.request.POST}') else: context['approved'] = self.object.approved return context HTML <form id="defForm" class="container-sm w-50" enctype="multipart/form-data" method="post" action="."> {% csrf_token %} {{ form.delete … -
Django models file update for many to many query
All, Here is my dilemma. I've created the Django models.py file with 2 classes, CustTeamMembers and CustTeamName. There is a many to many relationship between the two called cust_members. What this means is a team member can be on many teams and many teams can have the same member. What I need to create is a way to choose one member for each team that is a team leader. That team member needs to come from the cust_members list. So far I have not had any luck. Any help would be appreciated. My models.py file: from django.db import models # This will hold the team members class CustTeamMembers(models.Model): member_first_name = models.CharField(max_length = 100) member_last_name = models.CharField(max_length = 100) member_email = models.EmailField(unique=True) member_phone = models.CharField(max_length = 25, blank=True) class Meta(object): ordering = ['member_last_name'] def __str__(self): return self.member_first_name + ' ' + self.member_last_name # This will hold the customer name class CustTeamName(models.Model): cust_name = models.CharField(max_length = 100) #cust_lead = models.ForeignKey(CustTeamMembers, on_delete=models.CASCADE, blank=True) cust_members = models.ManyToManyField(CustTeamMembers, blank=True) cust_meet = models.CharField(max_length = 40, blank=True) cust_status = models.TextField(blank=True) def __str__(self): return self.cust_name def get_members(self): return ", ".join([str(p) for p in self.cust_members.all()] ~Ed -
Python OOP Design questions
I am currently building a Django application to track and analyse my stock porfolio. I currently have two [model] classes: Stock and Transaction. A stock holds information about a company and the transaction records all bought/sold shares from a stock. In my Stock class I have a 'stock' attribute. This is simply a holding attribute. All methods for updating this are done via the Transaction model (e.g. when I sell or buy shares). My reasoning is that everytime I view the object page, or call it, I don't have to perform a calculation to determin the amount of shares a stock own; this happens when we are selling or buying. The question I have is: is this a good way of writing software? Personally, I think this is a pros and cons case. But it would be nice to hear others thoughts and experiance. Perhaps I should just move the methods to the Stock model? Many things to consider here... Stock: class Stock(models.Model): """ Stock model refrences an organisation on the stock market. """ # DESC: Name of the company. name = models.CharField( unique=True, max_length=50, validators=[utils.alphabetical_chars_only] ) # DESC: Uniquely identifies a stock globally. isin = models.CharField( unique=True, verbose_name="ISIN", max_length=ISIN_LEN, … -
How to generate modelformset based on records in another model?
Suppose this is my model: class Question(models.Model): text = models.CharField(max_length=200) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) I want to create a modelformset from Answer model which automatically generates a form based on the number of records in Question model. model_formset = modelformset_factory(Answer, fields=('answer',), widgets = { 'answer': RadioSelect(choices=RATING_CHOICES),}) if request.method == "POST": form = model_formset(request.POST) if (form.is_valid()): # # # -
why can't I use my Django utilities, with django-admin
I installed Django with pip3 and got the up to date version but it says 'django-admin command not found'. I have python latest to, also when I tried to cd into the directory of Django admin but I failed. -
How to add manually on delete SQL constraints in Django?
In an existing Django project I experience critical performance issues when objects of a certain model are deleted. Actually the whole infrastructure breaks down. I'm pretty that this is caused by a foreign key field to another model with many and large entries. After several hours of googling I found a possible solution: Implementing on delete constraints on database level. I also found a long lasting discussion in a Django PR https://github.com/django/django/pull/8661 which would enable this feature. But I seems like it never reached 100% and will not be merged in the near future. Another way to solve my issue is mentioned in Django Docs https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.DO_NOTHING DO_NOTHING Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field. I'm using MariaDB. And I want to add a SET_NULL constraint to only one foreign key field of one model on database level. How can I do that in Django? I can perfectly live with hard coded ugly solutions, if they solve my problem and don't introduce new ones. -
SQL datetime2(7) field to Django [duplicate]
I need to rewrite this SQL column to a django model field DateCreated (datetime2(7), not null) what does the datetime2(7) exactly translate to? Many thanks in advance! -
Django Count lines in a Subquery
I need to count lines in a subquery and here is my solution for sqlite. class SQCount(Subquery): """Count lines in subquery""" template = "(SELECT count(*) FROM (%(subquery)s) _count)" output_field = models.IntegerField() sub = MyModel.objects.filter(user=OuterRef(OuterRef('id'))).values('id') qs = qs.annotate(count_total=SQCount(sub)) It works great for sqlite but not for MySQL (complains about Unknown column in 'where' clause). Any help appreciated. -
How can I get the ids of a queryset from a model and store them into a different model using a form?
I have a model called 'Competicion', with some objects and another model called 'Participante'. This second model has two fields: a foreignkey with the user and another foreingkey to 'Competicion'. In the view, I've made queryset from 'Competicion' and with a for loop in the template I've given each object the button of the form. With storing the user of the current session I have no problem but I want the form to know which object of the queryset it is to grab its id. #I have no problem with choices I just don't include them to save space Models.py class Competicion(models.Model): ciudad = models.CharField(max_length=50, null=True, choices=Ciudades_a_elegir, default="Ninguna") nombre = models.CharField(max_length=20, null=True, choices=Competiciones_a_elegir, default="Ninguna") titulo = models.CharField(max_length=40, null=True) fecha = models.DateField(null=True) participantes = models.IntegerField(null=True) flyer = models.ImageField(null=True, upload_to='imagenes', default='Ninguna') def __str__(self): return self.nombre + " " + self.titulo class Participante(models.Model): competicion = models.ForeignKey(Competicion, on_delete=models.CASCADE, null=True, blank=True) participantes = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.competicion.nombre + " " + self.competicion.titulo forms.py class ParticipanteForm(ModelForm): class Meta: model = Participante exclude = ['competicion', 'participantes'] views.py def competiciones(request): qs = Competicion.objects.all() form = ParticipanteForm(request.POST or None) if form.is_valid(): nombres = form.save() nombres.competicion = ???#Help me nombres.participantes = request.user nombres.save() return redirect('home') context = … -
Django: Refer to User objects in fixture for another model
To avoid the XY problem, I will describe my problem and my attempted solution separately. My problem I have an Appointment model which I want to write fixtures for. There is a one-to-many mapping from the Django User model to the Appointment model (every appointment has only one client, but a client can have multiple appointments). I know I can hard code the primary key for the Users in my appointment fixtures, but would be a brittle solution. Hard coding the foreign keys also compromises the readability of my fixtures. My attempted solution I looked at this question, which has an answer linking to Django documentation for natural keys. However, I ran into a problem attempting to use this approach. I believed I could create a proxy model for the User model, so I could create a custom Manager for natural keys. Here is my proxy model: class UserProxy(User): objects = UserManager # The UserManager class's code is omitted class Meta: proxy = True unique_together = [['username']] (If the UserManager class's code is relevant, please let me know in a comment, and I will add it.) However, when I run manage.py makemigrations, I get this error: ERRORS: accounts.UserProxy: (models.E016) 'unique_together' … -
Django Channels with Mongo DB - Python
I am trying to connect to mongo db using pymongo in my models.py and sending the connection object to UI using django channels. I wrote simple function to connect to mongo db using pymongo in my models.py like below models.py from django.db import models from pymongo import MongoClient def connectDB(): client = MongoClient('localhost', 27017) return client Now I have consumer.py to interact with my front end where in my websocket_connect method am calling connectDB() just to send the connection status to my UI. consumers.py from .models import connectDB async def websocket_connect(self, event): status = connectDB() await self.send({ "type": "websocket.accept", "text": status } ) here am just calling my connectDB() function which is there in my models to get the connection establishment status but throws error like below TypeError: 'Database' object is not callable. If you meant to call the 'encode' method on a 'MongoClient' object it is failing because no such method exists. how to solve this ? or is there any other way I can connect to db and send the status to UI using my consumers.py ? Thanks -
django - AbstractUser atributes gone ....?
so for some reason i get this error : $ python manage.py shell Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from auctions.models import * >>> u = User.objects.all() >>> u <QuerySet [<User: bob>]> >>> u.id Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'QuerySet' object has no attribute 'id' i did not set any primary key to overwrite djabgo's defaults (this is the code..) class User(AbstractUser): def __str__(self): return f"{self.username}" what is going on ??? -
How to initialize Django model fields whose loading was deferred?
I can overload the Model's __init__ to change the initialization behavior. But how to do the same when some of the model field loading are deferred? How do I run the initialization logic when that fields are loaded later? Is there something similar to def clean_field() that is called when the field is loaded later? -
How to create Route and View for HEAD http verb in Django Rest Framework
I would like to allow clients to send HTTP HEAD requests to my endpoint to allow them to check whether the resource exists without requiring the bandwidth to respond with the resource in the response body if it does. It should of course behave the same as GET but without sending the body of the response, just the header. I initially thought this would be handled by the DRF Router and ModelViewSet, but this question indicates that that isn't the case. Therefore I followed the advice in the answer posted there and wrote the following in urls.py and views.py: project/urls.py urlpatterns = [ path('api/resource/<str:value>', views.ResourceViewSet.as_view(actions={'head': 'retrieve', 'get': 'retrieve'})), app/views.py class ResourceViewSet(viewsets.ModelViewSet): serializer_class = serializers.ResourceSerializer queryset = Resource.objects.all() lookup_field = 'value' This setup isn't working for head requests. The get requests are all working as expected. Interestingly, the location and type of error I get depends on the client: From Postman client I get Parse Error: The server returned a malformed response in the Postman console. The DRF logs however show it giving the correct response code and there are no errors on the server. From CURL I get the correct response in the client, but the server throws a reset … -
Can anyone help me to implement hierarchical database in django or anyone has similar codes for the problem mentioned below?
I hope you will take this as a challenge. I want to make hierarchical database in django . This is a bit challenging to me and i am stuck here for many days and could not get solutions. Please help . Here i want to create is: Base class CellPhone N number of Brands for cellphones , N number of cellphone-models for each brands , N number of features for each models , N numbers of attributes for each feature and value associated with the attributes as shown in the picture above. This is the image how it should be implemented and appear on the admin: enter image description here enter image description here