Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"'str' object has no attribute 'get'" when passing slug to django form
I am attempting to pass a slug to a form, so that it can match user accounts with related groups (called 'events' in this project/context). The slug is an identifier for the event, which has several types of many-to-many connections to user-profiles (an extension to the standard django user model specifically made for connecting users to events). The form is supposed to create two drop-down choice fields to let an event manager set the permissions any other user has in the event, i.e. being a passive observer, an editor or a manager. However, as of now, django generates the error 'str' object has no attribute 'get' when rendering the page. The exception is located in django/forms/widgets.py in the function value_from_datadict, with the error being stated to be on line 0 in the base template base.dashboard.html, occurring during rendering. I've managed to avoid the error by removing both fields but leaving the slug and by removing both the candidate field and the slug, leaving the permissions field intact. I have also attempted to explicitly convert the passed value into a slug in the form (just in case some weird dynamic typing tripped the system up), but to no effect. What am … -
drf filter with related table count
Here is my model: class Artwork(models.Model): id = models.BigAutoField(primary_key = True) serial = models.IntegerField(choices=Serial.choices, default=100) title = models.CharField(max_length=255, blank=True, null=True) slug = models.CharField(max_length=255, blank=True, null=True) class Views(models.Model): id = models.BigAutoField(primary_key = True) user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name="views") artwork = models.ForeignKey(Artwork, null=True, blank=True, on_delete=models.CASCADE, related_name="views") Here is my view class GetArtworkLiteView(viewsets.ModelViewSet): queryset = Artwork.objects.all() serializer_class = GetArtworkLiteSerializer filter_backends = [filters.OrderingFilter, DjangoFilterBackend] filterset_fields = ['slug'] ordering_fields = ["id", "serial"] Here i want to make ordering by count(views) in artwork model. How can i add logic to that so artwork model will sort by count of views i wants to implement this using django rest framework -
Django model second update statement not working
I am working on Django 3.2 and trying to make multiple updates to different records in the same function. The model that I have is as following class PlayerData(models.Model): id = models.AutoField(primary_key=True, blank=False, null=False) is_playing = models.IntegerField(blank=True, null=True) current_team_name = models.CharField(max_length=50, blank=True, null=True) current_team_id = models.IntegerField(blank=True, null=True) I need to set is_playing flag as false for everyone which belongs to certain team. Which I am doing like this PlayerData.player.filter(current_team_name__in=teamInfo).update(is_playing=0) This update works perfectly. Next I need to iterate a dictionary and get some values and update the records with those values which I am doing this way for player in playerObj: playerId = player['id'] playerTeamData = playerTeamInfo[playerId] PlayerData.player.filter(id=playerId)\ .update(current_team_name=playerTeamData.split(":::")[0], current_team_id=playerTeamData.split(":::")[1], is_playing=1) This update statement doesn't work, neither I get any error nor the DB is updated. I am not sure what I am doing wrong. Do I need add some sort of commit statement between two updates? -
Invalid HTTP_HOST header: 'subdomain.domain.com'. You may need to add 'subdomain.domain.com' to ALLOWED_HOSTS
after two days From deplyoing my application and working fine, I have decided to change the name of the subdomain so i have just rename it under the path: /etc/nginx/sites-available and then i have did again sudo certbot --nginx for the "https" , then adding this host in settings.py from my django application, I have did sudo systemctl restart nginx to restart nginx then: sudo systemctl restart gunicorn then python manage.py makemigrations -->No changes detected python manage.py migrate -->No changes detected and when i go to the browser to access to my application I got this error DisallowedHost at / Invalid HTTP_HOST header: 'subdomain.domain.com'. You may need to add 'subdomain.domain.com' to ALLOWED_HOSTS. , otherwise i Have added the host on "settings.py" Help please isn't there any other step i should do when i change the host ,Thanks in advance -
Can you import django-signal function to another django file?
I have imported a function in my Store Model to get some information after i save a file in django-admin. Looks like this: @receiver(post_save, sender=Store) def update_from_crawl(instance, **kwargs): import time import os info = { 'api_url': instance.api_url, 'access_key': instance.access_key, 'c_key': instance.consumer_key, 'c_secret': instance.consumer_secret, } time.sleep(2) os.system("python manage.py woocommerce") return info Now in my woocommerce.py (custom django-admin command script) after importing update_from_crawl update_from_crawl() shows update_from_crawl() missing 1 required positional argument: 'instance' In the woocommerce.py file i have this variable which checks for wcapi = API( url="", consumer_key="", consumer_secret="", version="wc/v3" ) And i would like to pass the info['api_url'], info['c_key'], info['c_secret'] into this file everytime a model is saved and automatically run it. Do you have any idea how to pass it? I've tried so many things but i cant figure it out:) Thanks in advance -
How to request.data multiple files from postman?
I am having a file field "documents" in which I want to add multiple files. But when I do documents = request.data('documents[]') I only get the last selected file. How can I get all the files as a list in documents variable. -
Should we use django authentication for all users of a site?
I have just started developing a bookstore site with Django and I have a question about user authentication. I want users to have a wallet, shopping cart and additional information for their account such as profile picture, phone number, address, etc. to buy books. And now I am faced with the dilemma of whether to change the User model itself, or create a Profiles model for each and link it to the User model, or create a separate model (in other words, the authentication system) and do everything from scratch. Now I have started building a separate authentication system. Everything was going well until I had problems in sending and receiving user data in the template contexets. Finally, in general, I want to know if Django authentication system is really suitable for all users of a site? -
Django, ImportError: cannot import name 'task' from 'celery'
I have Django application that was using Celery version 4.4.2, which was working fine. from celery import task import logging @task(ignore_result=True) def log_user_activity(user_id): try: logging.info(user_id) except Exception as e: logging.error(str(e)) As I tried to update the Celery version to v5.2.2 I get below error: ImportError: cannot import name 'task' from 'celery' Can someone help what is task been replaced with? they still have example here with same. https://github.com/celery/celery/blob/v5.2.2/examples/celery_http_gateway/tasks.py -
Filtering a Django model on an AutoField
I have a Django model that looks like this - class History(models.Model): testcaseidstring = models.AutoField(primary_key=True) # Field name made lowercase. I am storing String values in this field in the Database When I make a query on this field like - qs=qs.filter(testcaseidstring="tc123") I get an error saying "Field 'testcaseidstring' expected a number but got 'TC123'" How can I filter on this AutoField? Is converting that field to a TextField the only way to go? Any help would be highly appreciable Thanks!! -
You are trying to change the nullable field 'email' on customuser to non-nullable without a default
I have two models (UserAddress and CustomUser) in my models.py, the field user address in CustomUser was a many to many field but I decided to change it to a foreign key field. But when I ran python manage.py make migrations it asked me to choose a choice: what should I do: You are trying to change the nullable field 'email' on customuser to non-nullable without a default; we can't do that (the database needs something to populate exis ting rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous dat a migration) Quit, and let me add a default in models.py Here is my models.py file: class UserAddress(models.Model): city = models.CharField(max_length=100) address = models.CharField(max_length=200) zip_code = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.id) class CustomUser(AbstractUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) user_address = models.ForeignKey(UserAddress, on_delete=models.CASCADE) -
How AWS S3 requests are made/calculated?
I am new to AWS. I have created a S3 bucket a few days ago and I have noticed the number of requests made to it is already very high. Over the free tier limit for Put... I don't understand what is going on. I did connect a django heroku hosted app to the bucket but I am the only one having access to it and I only made a dozens of requests in the past few days. Can you please help me understand what is going on, is this normal behaviour? I didn't find my answer on Amazon forum and to access the technical support I need to upgrade my plan... Thank you -
How to pass django-simple-history model in Graphene-Django?
I have created an instance of simple_history.models.HistoricalRecords in my Notification model models.py class Notification(models.Model): title = models.CharField(max_length=500) content = RichTextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) history = HistoricalRecords() class Attachment(models.Model): title = models.CharField(max_length=500) attachement = models.FileField(upload_to = user_directory_path) notifiaction = models.ForeignKey(Notification, on_delete=models.SET_NULL, null= True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) schema.py class AttachmentNode(DjangoObjectType): class Meta: model = Attachment filter_fields = ['title'] interfaces = (relay.Node, ) class NotificationNode(DjangoObjectType): class Meta: model = Notification filter_fields = { 'id': ['exact'], 'title': ['exact', 'icontains', 'istartswith'], } interfaces = (relay.Node, ) class Query(graphene.ObjectType): notifications = relay.Node.Field(NotificationNode) all_notifications = DjangoFilterConnectionField(NotificationNode) This is working fine but I want all the records in the graphql endpoint of HistoricalRecords() as well. How can I do this? -
Regarding Database is locked in Azure Django
I have an App service running django app on free service on linux. it is resetting my db.sqlite3 file again and again and i can not afford to use postgresql as it is not in free services (I don't have azure free credit). How can i make db.sqlite3 file persistent? Things I have tried :- tried adding db.sqlite3 in /home/site/wwwroot/ but django is showing that database is locked. created dbfiles directory in /tmp folder and added db.sqlite3 in /tmp/dbfiles but django is showing that unable to open database file. AS I NEED IT URGENT PLEASE HELP -
Django and Tox testing
I have a django package that I like to test against different versions of django using tox and with the python manage.py test command. On the newer versions, django has from django.urls import reverse available, but this doesnt exist on e.g. Django 1.8, because its in a diff path, but this version I am trying to test against, too. Can someone point me to resources to find out how I can still make the tox testing pass? Whats the correct way of testing this? Is there some sort of conditional import I can do based on django version? Or maybe sth like try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse Im just not sure if this is the standard and safest way :) Thanks! tox config [tox] envlist = {py27,py35}-django18, {py27,py35}-django19, {py27,py35}-django110, {py27,py35,py36,py37}-django111, {py35,py36,py37}-django20, {py35,py36,py37}-django21, {py35,py36,py37}-django22, {py35,py36,py37,py38}-django30, {py38,py39,py310}-django40, [testenv] commands = python manage.py test deps = django18: django==1.8.* django19: django==1.9.* django110: django==1.10.* django111: django==1.11.* django20: django==2.0.* django21: django==2.1.* django22: django==2.2.* django30: django>=3.0a1,<3.1 django40: django==4.0.* -
unable to get the data from url to do predictions in django rest api
I was trying to do predictions in drf and celery and my tasks.py file is @shared_task(bind=True) @api_view(['GET']) def predictions(self): solute = request.GET.get('solute') solvent = request.GET.get('solvent') mol = Chem.MolFromSmiles(solute) mol = Chem.AddHs(mol) solute = Chem.MolToSmiles(mol) solute_graph = get_graph_from_smile(solute) mol = Chem.MolFromSmiles(solvent) mol = Chem.AddHs(mol) solvent = Chem.MolToSmiles(mol) solvent_graph = get_graph_from_smile(solvent) delta_g, interaction_map = model([solute_graph.to(device), solvent_graph.to(device)]) return delta_g.detach(), torch.trunc(interaction_map).detach() and my views.py file is @api_view(['GET']) def result(request): response = {} results = predictions.apply_async() # response["interaction_map"] = (results[1].numpy()).tolist() # final_results = results.get() print(results.get(propagate=False)) # response["predictions"] = results[0].item() return Response({'result': results.get(propagate=False)}, status=200) I am getting error @api_view(['GET']) NameError: name 'api_view' is not defined. I know that loading the solute and solvent in the views.py file rectifies the problem. but I want to get them directly in the tasks.py file. If not possible I want to bring the solute and solvent to the tasks.py file. How can i do it? solute = request.GET.get('solute') solvent = request.GET.get('solvent') -
How to implement a hotel room pickup app?
I'm working on a Django app which would take data on the numbers of rooms sold in a hotel for each (future) date, on any given date, and use that data to determine pickup rate. For example, this is what the data for 12/22/2021 might look like: Date Rooms Sold Days Prior 12/23/2021 34 1 12/24/2021 19 2 12/25/2021 11 3 12/26/2021 10 4 12/27/2021 3 5 So on 12/22, the hotel had 34 rooms sold for the night of 12/23, 10 rooms sold for the night of 12/26, and so on. My goal for this app is to compare how the numbers are changing to determine the pickup rate for a given date. For example, if on 12/25 the hotel had 20 rooms sold for the night of 12/26, then I would be able to see that the pickup for that date/night was 10 rooms over the course of 3 days (because there was 10 rooms sold on 12/22). I would want dates to get flagged if there was a sudden pickup in rooms sold on that date, signaling a possible event and increase in demand for rooms that day. I'm just having trouble figuring out how I should … -
I have trouble in editing a post in django project
I am working on a Django project where I can create a post and also edit a specific post using the post's id. views.py @login_required def editpost(request,id): postform = NewPost.objects.get(id=id) if request.method == "GET": post = NewPostForm(request.GET, instance=postform) user = request.user.id timestamp = datetime.now() if post.is_valid: post = post.save() postdata = post.save(id = id,post = post,user = user,timestamp = timestamp) postdata.save() return HttpResponseRedirect(reverse("index")) return render(request,"network/postform.html",{ "postform" : postform, "id" : id, }) urls.py urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("postform", views.createpost, name="postform"), path("editform/<int:id>",views.editpost,name="editpost"), ] editform.html {% extends 'network/layout.html' %} {% block body %} <div style="margin: 70px 10px 10px 10px;"> <!-- <h1>Create New Post</h1> --> <div class="border border-success" style="margin: 10px 10px 10px 10px; position: relative;"> <div style="margin: 10px 10px 10px 10px;"> <label>New post</label> <form id="NewPostForm" action="{% url 'index' %}" method="GET"> {% csrf_token %} <div class="form-group"> {{ postform }} </div> <input class="btn btn-success" type="Submit" value="Submit"> </form> </div> </div> </div> {% endblock %} I have trouble routing my template. What should I do now!? -
Is it possible to not use styles.css for a specific div or tag, but instead use tailwind css?
I basically want to stop a div or a button from being influenced by my styles.css, since I want to only use tailwind css for that tag. Basically I want something like below, if it is possible: <button class="stop-being-influenced-by-styles.css flex border-0...other tailwind css">Button</button> Thank you, and please leave any comments if you have a question. -
How to deploy machine learning model
I have a trained model saved as main_model.sav, this model is trained based on phishing website dataset of 60 columns. Now I will like to deploy the model so that I can test any website of my choice. The online tutorial I have seen so far on deployment of machine learning model simply asks all the parameters used by the model to make prediction and when the user fills the information, the application will output the prediction.For example, this dataset used by this author will simply ask the user the Sepal_Length, Sepal_Width, Petal_Length and Petal_Width to get the class prediction which is extremely easy and similar to all I am seeing online. For the phishing website dataset, after been trained, it will only make sense to ask the URL alone and the model will predict if it's phishing or not just like phishtank. My question is that, how do we deploy a machine learning model that is trained with several X-columns (like 60 columns) and expected to get only one information (URL in this case) to make the binary prediction (phishing =1, not phishing =0)? Please I will appreciate it if there is any post (or guide) that I am … -
Django Rest Frame Work: passing User in djago rest frame work
I have a Django project as following code in model class Report(models.Model): created_by_user=models.ForeignKey(User,on_delete=models.CASCADE) following code in serializer class ReportSerializer(serializers.ModelSerializer): class Meta: model=Report fields='__all__' and following code in view class ReportCreateView(APIView): def post(self,request, *args, **kwargs): received_data=ReportSerializer(data=request.data) if received_data.is_valid(): received_data.save() return Response(received_data.data, status=status.HTTP_201_CREATED) return Response(received_data.errors,status.HTTP_400_BAD_REQUEST) when I send a post request by postman and send username and password in Authorization tab it error: { "created_by_user": [ "This field is required." ] } but if I type username or password incorrect it will be { "detail": "Invalid username/password." } can everybody help me? -
TypeError: Object of type DeferredAttribute is not JSON serializable
While testing my project, I found this weird error: Object of type DeferredAttribute is not JSON serializable... Before jump into the error, I want to tell what I wanted: Step 1: Registered User share his/her refer code so other person. Step 2: Unregistered person enters the code in the link. Step 3: The browser shows the button to continue to create account This is urls.py file ''' from django.contrib import admin from django.urls import path, include from core import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home), path('<str:code>/SS', views.home), path('accounts/', include('accounts.urls')), # path('', include('accounts.urls')), ] ''' This is views.py file ''' from django.shortcuts import render from accounts.models import Refer def home(request, *args, **kwargs): code = str(kwargs.get('code')) try: user = Refer.objects.get(referral_code = code) print(user.referral_code) request.session['ref_profile'] = Refer.id print('id', user.id) except: pass print(request.session.get_expiry_date()) return render(request, 'accounts/registration.html') ''' A simple home.html file ''' {% extends 'base.html' %} {% block title %} home {% endblock title %} {% block bodycontent %} {% if user.is_authenticated %} {{user}} {% else %} <p> "Hello Everyone" </p> <button class="btn btn-primary"><a href="{% url 'accounts:registration' %}">Create New User</a></button> {% endif %} {% endblock bodycontent %} ''' And I got this ''' Request Method: GET Request URL: http://127.0.0.1:8000/de829fab192047/ Django Version: 4.0.1 … -
Is it okay to have two base.html templates in django?
Is it okay to have multiple base.html templates in django? For instance, I would have one template that would extend from base_one.html and another template extending from base_two.html. For example, this is one of the templates: {% extends "base_one.html" %} {% block content %} {% endblock content %} and this is another template: {% extends "base_two.html" %} {% block content %} {% endblock content %} -
UNIT TEST- Django DRF - How to calling methods in ModelViewSets (Avoid 404 Error)
I am writing unit test code for viewsets. I often struggling for calling url to access my methods. here, views.py class AppraisalEmployeeAPI(viewsets.ViewSet): def get_permissions(self): if self.action in ['retrieve']: self.permission_classes = [IsOwnerPermission | IsHODPermission | IsHRUser | IsManagementUser] elif self.action in ['list']: self.permission_classes = [IsHRUser | IsManagementUser] return super(self.__class__, self).get_permissions() def list(self, request): # code return obj def retrieve(self, request): #code return obj urls.py router = routers.DefaultRouter() router.register('appraisal', AppraisalAPI) router.register(r'employee', AppraisalEmployeeAPI, basename='employee') urlpatterns = [ path('', include(router.urls)), ] test.py url = reverse('employee-list') self.client = Client(HTTP_AUTHORIZATION='Token ' + token.key) resp1 = self.client.get(url, format='json') self.assertEqual(resp1.status_code, 200) Here, I have got 404 page not found response. I dont know how to approach viewssets by using url routers. Expecting help for above issue and how to approach viewsets and router urls. Thanks in Advance,..... -
reverse(thing) django rest framework in a viewset
The main question is: What is the rest framework ViewSet friendly way to make the reverse routes? In a django cookiecutter site I have api_router.py with this router.register(r"users", UserViewSet) router.register(r"userprofile", UserProfileViewSet, basename="userprofile") router.register(r"student", StudentViewSet) urlpatterns = router.urls app_name = "api" print(f"we have routes") for route in router.urls: print(route) print(f"{reverse('student-list') = }") which errors out saying that reverse can't find student-list the student model.py has a StudentViewSet with the standard class StudentViewSet( RetrieveModelMixin, CreateModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet, ): so it should have the stuff needed to create the student-list the output of that print statement is showing student-list **** edited ....*** athenaeum_local_django | <URLPattern '^student/$' [name='student-list']> athenaeum_local_django | <URLPattern '^student\.(?P<format>[a-z0-9]+)/?$' [name='student-list']> athenaeum_local_django | <URLPattern '^student/(?P<userprofile__user__username>[^/.]+)/$' [name='student-detail']> athenaeum_local_django | <URLPattern '^student/(?P<userprofile__user__username>[^/.]+)\.(?P<format>[a-z0-9]+)/?$' [name='student-detail']> The end of the error is as follows: ahenaeum_local_django | File "/app/config/urls.py", line 29, in <module> athenaeum_local_django | path("api/", include("config.api_router")), athenaeum_local_django | File "/usr/local/lib/python3.9/site-packages/django/urls/conf.py", line 34, in include athenaeum_local_django | urlconf_module = import_module(urlconf_module) athenaeum_local_django | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module athenaeum_local_django | return _bootstrap._gcd_import(name[level:], package, level) athenaeum_local_django | File "<frozen importlib._bootstrap>", line 1030, in _gcd_import athenaeum_local_django | File "<frozen importlib._bootstrap>", line 1007, in _find_and_load athenaeum_local_django | File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked athenaeum_local_django | File "<frozen importlib._bootstrap>", line … -
Django Form is not processing properly and no error has been displayed
Trying to create an app that saves sales in different sateges for my team(similar to an ecommerce) however the form to add the account info is not saving the data... I review different options and use formset as well no changes. model.py TYPE=( ('delegated','Delegated'), ('not_delegated','Not Delegated') ) class Account(models.Model): agent_profile=models.ForeignKey(AgentProfile, on_delete= CASCADE) account_name=models.CharField(max_length=120) opp_type=models.CharField(max_length=20, choices=TYPE, default='not_delegated') bp_id=models.IntegerField() mdm_id=models.CharField(max_length=50, null=True,blank=True) AM=models.CharField(max_length=50,null=True,blank=True) def __str__(self): return str(self.agent_profile) forms.py from django.forms import ModelForm from .models import Account class AccountForm(ModelForm): class Meta: model=Account fields=[ #'agent_profile', 'account_name', 'opp_type', 'bp_id', 'mdm_id', 'AM' ] views.py def confirm_account_create_view(request): form=AccountForm(request.POST or None) context = { "form": form } next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): instance=form.save(commit=False) agent_profile, agent_profile_created = AgentProfile.objects.new_or_get(request) if agent_profile is not None: opp_type = request.POST.get('delegate_opp', 'not_delegated_opp') instance.agent_profile = agent_profile instance.opp_type = opp_type instance.save() request.session[opp_type + "_opp_id"] = instance.id print(opp_type + "_opp_id") else: print("Please verify Form") return redirect("opps:confirm") if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) return redirect("opps:confirm") urls.py (main app) path('orders/confirm/account', confirm_account_create_view, name='create_account'), form page(HTML) {% csrf_token %} {% if next_url %} {% endif %} {% if opp_type %} <input type='hidden' name='opp_type' value='{{ opp_type }}' /> {% endif %} {{ form.as_p }} <button type='submit' class='btn btn-default'>Submit</button> </form> confirm page(HTML) {% extends "base.html" …