Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can check availability domain name by using Python?
I'm trying to make a script that returns unregistered domains. How can I find an available domain name? -
Django REST framework how to create new User?
I'm now trying since two days getting stupid POST requests into my Django application using the Django REST framework but fir some reason i always fail getting a request trough. Either I get a permission error when creating a class based view. if I create a function based view I always run into validation error and im kind of frustrated about the complexity of DRF. Have a look at the following view to create a User object: views.py @api_view(['GET', 'POST']) @permission_classes([AllowAny]) def user_create(request): if request.method == 'POST': print(request.data) serializer = CreateUserProfileSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({ "user": UserSerializer(user, context=serializer.data) }) serializers.py class CreateUserProfileSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ('id', 'user',) extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create( validated_data['user'], validated_data['password']) user.save() return user error when sending a POST to the endpoint: File "/App/App_API/serializers.py", line 36, in create validated_data['password']) KeyError: 'password' Why that? If I do the following at my views code: print(request.data) I see the following at the console: <QueryDict: {'user': ['peter432'], 'password': ['OUBIfwiowef']}> Can somebody please share his way of creating a user. -
Why is setState callback state turning to "undefined" after populated with data?
I am trying to create a product with an image from browser. For the image field, I have a separate component to crop the image. // part of createProduct form. // this is a separete component. i passed callback to the set the image url <FileLoader onFileUpload={setImage}></FileLoader> <Form.Group controlId="brand"> <Form.Label>Brand</Form.Label> <Form.Control type="text" placeholder="Enter brand" value={brand} onChange={(e) => setBrand(e.target.value)} ></Form.Control> </Form.Group> My goal is to set the image, upload it first to Django, Django will return the url for S3 bucket, I will use that url to pass along with the createProduct form. inside FileLoader component, this is how I send the post request: const uploadFileHandler = async (image: File) => { const formData = new FormData(); formData.append("image", image); const config = { headers: { "Content-Type": "multipart/form-data", Authorization: `Bearer ${userInfo?.token}`, },}; return axios .post( `${process.env.DJANGO_API_URL!}/api/products/upload-image/`, formData, config ) // onFileUpload is callback to set the image in parent component .then((res) => onFileUpload(res.data)); }; This actually works. I get the url but as soon as I get it, it becomes undefined. What could be the reason? I also logged the "name" of the product and that state still persisted and also posted to the backend when I submit the form -
How to setup Django permissions to be specific to a certain model's instances?
Please consider a simple Django app containing a central model called Project. Other resources of this app are always tied to a specific Project. Exemplary code: class Project(models.Model): pass class Page(models.Model): project = models.ForeignKey(Project) I'd like to leverage Django's permission system to set granular permissions per existing project. In the example's case, a user should be able to have a view_page permission for one project instance, and don't have it for another instance. Is there a way to extend or replace Django's authorization system to achieve something like this? I could extend the user's Group model to include a link to Project and check both, the group's project and its permissions. But that's not elegant and doesn't allow for assigning permissions to single users. Would a project like django-guardian make sense here to gain object-level permissions? It feels like a quite bit of overhead for something that doesn't need that kind of granularity. -
Does save() function in Django overwrite older data in the DB table?
I am working on a Django app that works on two Databases, like so: Oracle DB(to fetch the data on an hourly basis) MySql DB (to save the processed data fetched from the Oracle DB) My Database config in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dashboard', 'USER': 'db1', 'PASSWORD': 'password1', 'HOST': 'localhost', 'PORT': '3306', }, 'MBDB': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xe', 'USER': 'db2', 'PASSWORD': 'password2', 'HOST': 'localhost', 'PORT': '1521', } } My Django-Model: class Transactions(models.Model): class Meta: db_table='TRANSACTIONS' unique_together=(("TIME_UPDATED","TRAN_TYPE"),) indexes=[ models.Index(fields=["TIME_UPDATED","TRAN_TYPE"]), models.Index(fields=["TRAN_TYPE"]) ] TIME_UPDATED = models.DateTimeField() TRAN_TYPE = models.CharField(max_length=32,primary_key=True) SUCCESS = models.IntegerField() TECHNICAL_DECLINES = models.IntegerField() BUSINESS_DECLINES = models.IntegerField() TOTAL = models.IntegerField() PERCENTAGE_TECH_DEC = models.FloatField() def __str__(self): return self.TRAN_TYPE def save(self,D,tran): self.TIME_UPDATED=D self.TRAN_TYPE=T=tran['Type'] self.SUCCESS=S=int(tran['Success']) self.TECHNICAL_DECLINES=TD=int(tran['Tech_dec']) self.BUSINESS_DECLINES=BD=int(tran['Bus_dec']) self.TOTAL=total=S+TD+BD if total==0:#division by zero error constraint self.PERCENTAGE_TECH_DEC=0 else: self.PERCENTAGE_TECH_DEC=((TD/(total))*100) super(Transactions,self).save() Here the column ```TRAN_TYPE`` is defined as the primary key and both ```TRAN_TYPE``` AND ```TIME_UPDATED``` are composite primary keys as defined in ```Class Meta```. Sample-Queryset from views.py: {'SERVICE_CODE': 'IBKREVERSAL', 'Type': 'IBKREVERSAL', 'Success': 1, 'Tech_dec': 4, 'Bus_dec': 0} Queryset processed and saved @ Transactions on October 14, 2021 - 17:25:20: {'TIME_UPDATED': datetime.datetime(2021, 10, 14, 17, 25, 20, tzinfo=<UTC>), 'TRAN_TYPE': 'IBKREVERSAL', 'SUCCESS': 1, 'TECHNICAL_DECLINES': 4, 'BUSINESS_DECLINES': 0, 'TOTAL': 5, 'PERCENTAGE_TECH_DEC': Decimal('80.000')} Now when … -
Django BooleanField in Angular
I am building an App with Django as my backend and Angular as my frontend. In Django I have a BooleanField for my class "Employee". They can tick, if they are planning on being retired in 5 years or not: class Employee(models.Model): name = ... retired_5 = models.BooleanField(default = False) I have serialized my class and set up my REST API. class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('id', 'name', 'retired_5', ..., 'url') In Angular I build a form, that can create a new Employee. Without the Boolean field, it works: <mat-form-field> <mat-label>Name</mat-label> <input matInput [(ngModel)]="employee.name"> </mat-form-field> <button [mat-dialog-close]="employee" cdkFocusInitial> Add </button> But when I try to add the BooleanField, I am not able to add new employee: <section [(ngModel)]="employee.retired_5"> <mat-checkbox>Retired in the next five years</mat-checkbox> </section> Any idea on how to properly add BooleanField from Django and integrate into Angular? -
How to change status of the model in Django
I'm building a small to-do list project using Django, the to-do list has tasks divided into to-do, in-progress and done, I want to move to-do tasks from todo list to in- progress list, so I gave the to-do model 3 status, but I'm not sure how to set the status. Any help would be appreciated. models.py ''' class Todo(models.Model): status_option = ( ('to_do', 'to_do'), ('in_progress', 'in_progress'), ('done', 'done'), ) status = models.CharField(max_length=20, choices=status_option, default='to_do') project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=20) create_date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField(default=datetime.datetime.now) due_date = models.DateTimeField(default=datetime.datetime.now) details = models.TextField() def __str__(self): return self.status ''' views.py ''' def add_to_progress(request, todo_id, project_id): todo = Todo.objects.get(id=todo_id) project = Project.objects.get(id=project_id) if request.method != 'POST': form = dragTodoForm() else: form = dragTodoForm(request.POST) Todo.objects.filter(id=todo_id).update(status='in_progress') context = {'form', form, 'todo', todo, 'project', project} return render(request, 'todo_lists/new_progress.html', context) def add_to_done(request, todo_id, project_id): todo = Todo.objects.get(id=todo_id) project = Project.objects.get(id=project_id) if request.method != 'POST': form = dragTodoForm() else: form = dragTodoForm(request.POST) Todo.objects.filter(id=todo_id).update(status='done') context = {'form', form, 'todo', todo, 'project', project} return render(request, 'todo_lists/new_done.html', context) ''' -
How to access user information in utils.py in django (how to filter a model queryset)
I am trying to access the user information in utils.py, but don't know how. I need something like below(self.request.user) that was used for views.py: def get_context_data(self, **kwargs): context = super(ListView, self).get_context_data(**kwargs) user = self.request.user if user.is_student: queryset = Lead.objects.filter( status__exact="n" ) return context However, if you could help me solve a more fundamental problem of why I am trying to do this in the first place, it would be really helpful. You see, I am trying to run the view below in my django website: class CalendarView(LoginRequiredMixin, generic.ListView): model = Class template_name = 'leads/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # use today's date for the calendar d = get_date(self.request.GET.get('month', None)) # Instantiate our calendar class with today's year and date cal = Calendar(d.year, d.month) # Call the formatmonth method, which returns our calendar as a table html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context However, when I add the below code, it does not filter the model Class before rendering the calendar. Therefore, I end up going through all of the instances in the Class model. def get_queryset(self): return Class.objects.filter(date=datetime.date(1111,11,11)) Of course, I am going to edit the function above to use the … -
AttributeError: module 'tensorflow.python.training.experimental.mixed_precision' has no attribute '_register_wrapper_optimizer_cls' when deploying
I am getting the above error when trying to run a python django program on a windows server. The program works fine when I run it on my own laptop. The versions of keras and tensorflow and other libraries are as follows: absl-py==0.13.0 altgraph==0.17 argon2-cffi==20.1.0 asgiref==3.4.1 astunparse==1.6.3 async-generator==1.10 attrs==21.2.0 backcall==0.2.0 beautifulsoup4==4.9.3 bleach==4.0.0 bs4==0.0.1 cachetools==4.2.2 certifi==2021.5.30 cffi==1.14.6 chardet==4.0.0 clang==5.0 click==8.0.1 colorama==0.4.4 cycler==0.10.0 Cython==0.29.23 dearpygui==0.8.64 debugpy==1.4.1 decorator==5.0.9 defusedxml==0.7.1 Django==3.2.7 django-rest-framework==0.1.0 djangorestframework==3.12.4 entrypoints==0.3 filelock==3.0.12 flatbuffers==1.12 future==0.18.2 gast==0.4.0 gensim==4.1.0 google-auth==1.32.1 google-auth-oauthlib==0.4.4 google-pasta==0.2.0 graphviz==0.17 grpcio==1.40.0 h5py==3.1.0 huggingface-hub==0.0.12 idna==2.10 imbalanced-learn==0.8.0 ipykernel==6.0.3 ipython==7.25.0 ipython-genutils==0.2.0 ipywidgets==7.6.3 jedi==0.18.0 Jinja2==3.0.1 joblib==1.0.1 jsonschema==3.2.0 jupyter-client==6.1.12 jupyter-core==4.7.1 jupyterlab-pygments==0.1.2 jupyterlab-widgets==1.0.0 keras==2.6.0 keras-nightly==2.5.0.dev2021032900 Keras-Preprocessing==1.1.2 kiwisolver==1.3.1 libclang==11.1.0 Markdown==3.3.4 MarkupSafe==2.0.1 matplotlib==3.4.2 matplotlib-inline==0.1.2 mistune==0.8.4 nbclient==0.5.3 nbconvert==6.1.0 nbformat==5.1.3 nest-asyncio==1.5.1 nltk==3.6.2 notebook==6.4.1 numpy==1.19.5 oauthlib==3.1.1 opt-einsum==3.3.0 packaging==21.0 pandas==1.3.0 pandocfilters==1.4.3 parso==0.8.2 pefile==2021.9.3 pickleshare==0.7.5 Pillow==8.3.0 prometheus-client==0.11.0 prompt-toolkit==3.0.19 protobuf==3.17.3 py2exe==0.10.4.1 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.20 pydot==1.4.2 pydotplus==2.0.2 Pygments==2.9.0 pyinstaller==4.5.1 pyinstaller-hooks-contrib==2021.3 pyparsing==2.4.7 pyrsistent==0.18.0 PySimpleGUI==4.47.0 python-dateutil==2.8.1 pytz==2021.1 pywin32==301 pywin32-ctypes==0.2.0 pywinpty==1.1.3 PyYAML==5.4.1 pyzmq==22.1.0 regex==2021.8.3 requests==2.25.1 requests-oauthlib==1.3.0 rsa==4.7.2 sacremoses==0.0.45 scikit-learn==0.24.2 scipy==1.7.0 seaborn==0.11.1 Send2Trash==1.7.1 six==1.15.0 smart-open==5.2.1 soupsieve==2.2.1 sqlparse==0.4.2 tb-nightly==2.7.0a20210914 tensorboard==2.6.0 tensorboard-data-server==0.6.1 tensorboard-plugin-wit==1.8.0 tensorflow==2.6.0 tensorflow-estimator==2.6.0 tensorflow-io-gcs-filesystem==0.21.0 termcolor==1.1.0 terminado==0.10.1 testpath==0.5.0 tf-estimator-nightly==2.7.0.dev2021091608 Theano==1.0.5 threadpoolctl==2.1.0 tokenizers==0.10.3 torch==1.9.0 tornado==6.1 tqdm==4.62.0 traitlets==5.0.5 transformers==4.9.1 typing-extensions==3.7.4.3 UNKNOWN==0.0.0 urllib3==1.26.6 waitress==2.0.0 wcwidth==0.2.5 webencodings==0.5.1 Werkzeug==2.0.1 widgetsnbextension==3.5.1 wordcloud==1.8.1 wrapt==1.12.1 yellowbrick==1.3.post1 I am not sure what the problem is since its running on my … -
AnonymousUser error on unauthenticated route Django
I am basically a FE developer. Recently I am trying to edit a Django project and remove authentication from an api. So after removing the authentication and trying to get the data without the token it shows an anonymous error. Works good for valid user django_1 | return method(value) django_1 | File "/app/deals/serializers.py", line 285, in get_already_liked django_1 | return usr.is_liking_deal(deal_obj=obj) django_1 | AttributeError: 'AnonymousUser' object has no attribute 'is_liking_deal' Here is the specific code in the serializers def get_already_liked(self, obj): usr = self.context["request"].user return usr.is_liking_deal(deal_obj=obj) After digging into the issue and researching I found out it is an issue with the model and primary key. as I am not sending an user through authentication Django is taking it as AnonymousUser and in the model AnonymousUser doesnt have any primary key.Here is the related code from the model (I think) class DealReactionManager(models.Manager): @staticmethod def is_user_liking_deal(user, deal): """Has user liked the deal already?""" try: DealReaction.objects.get(user=user, deal=deal) return True except DealReaction.DoesNotExist: return False class DealReaction(BaseModel): deal = models.ForeignKey(to="deals.Deal", related_name="reactions", on_delete=models.CASCADE) user = models.ForeignKey(to=get_user_model(), related_name="reactions", on_delete=models.CASCADE) objects = DealReactionManager() class Meta: unique_together = ("deal", "user") What I can understand from this is, after calling the deals api it looks for the liked deals … -
React's "npm run build" command gives error while running in "Virtual environment"
I'm trying to use react for front-end in Django project in a virtual environment. Steps I followed, Create a virtual environment Create a Django project in the same folder Create a react app in the same folder cd to react app Run "npm run build" I'm getting an error here saying, "'Export' is not recognized as the internal or external command" Log, ''' 0 info it worked if it ends with ok 1 verbose cli [ 1 verbose cli 'C:\\Program Files\\nodejs\\node.exe', 1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js', 1 verbose cli 'run', 1 verbose cli 'build' 1 verbose cli ] 2 info using npm@6.14.15 3 info using node@v14.18.0 4 verbose run-script [ 'prebuild', 'build', 'postbuild' ] 5 info lifecycle frontend@0.1.0~prebuild: frontend@0.1.0 6 info lifecycle frontend@0.1.0~build: frontend@0.1.0 7 verbose lifecycle frontend@0.1.0~build: unsafe-perm in lifecycle true 8 verbose lifecycle frontend@0.1.0~build: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;D:\code\PortfolioOct21\frontend\node_modules\.bin;D:\code\PortfolioOct21\venv\Scripts;C:\Program Files\AdoptOpenJDK\jdk-11.0.11.9-hotspot\bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files\Python39\Scripts\;C:\Program Files\Python39\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Git\cmd;C:\MinGW\bin;C:\Program Files\nodejs\;C:\Program Files\MySQL\MySQL Shell 8.0\bin\;C:\Users\himan\AppData\Local\Microsoft\WindowsApps;C:\Chromedriver;C:\Program Files\Python39\Scripts;C:\Users\himan\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\himan\AppData\Roaming\Python\Python39\Scripts;C:\Program Files\heroku\bin;C:\Program Files\nodejs\;C:\Program Files\JetBrains\PyCharm Community Edition 2021.2\bin;;C:\Users\himan\AppData\Roaming\npm 9 verbose lifecycle frontend@0.1.0~build: CWD: D:\code\PortfolioOct21\frontend 10 silly lifecycle frontend@0.1.0~build: Args: [ 10 silly lifecycle '/d /s /c', 10 silly lifecycle 'export NODE_ENV=production && rm -rf ./build && webpack --env.production --optimize-minimize' 10 silly lifecycle ] 11 silly lifecycle frontend@0.1.0~build: Returned: code: … -
Sorting (order_by) in list
I am building a BlogApp and I am trying to sort or order_by in list which contains multiple queries. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) date = models.DateTimeField(auto_now_add=True) class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) blog_of = models.ForeignKey(BlogPost, on_delete=models.CASCADE) body = models.CharField(max_length=30) date_added = models.DateTimeField(auto_now_add=True) views.py def mypage(request): query_1 = list(BlogPost.objects.filter(user=request.user).order_by('-date')) query_2 = list(Comment.objects.filter(user=request.user).order_by('date_added')) results = sorted(chain(query_1, query_2),key=attrgetter('date') , reverse=True) context = {'results':results} return render(reques, 'mypage.html', context) But is showing 'Comment' object has no attribute 'date' And I think this is because date field name is different in both model and i am querying with only one, But i have no idea how can I sort with different field name. Any help would be much Appreciated. Thank You -
How to get and match categories in a specific root of categories to be saved to the database?
Good day to all. You need to get all the id from the root category, and pass it to the creation of the model. At the moment I am doing it like this: game = driver.find_element_by_class_name('breadcrumbs').find_elements_by_tag_name('a')[0].text #root cat data_categories = driver.find_elements_by_class_name('rightDetailsBlock')[0].find_elements_by_tag_name('a') # I get categories that need to be mapped to the category root root_category = Category.objects.get(slug=game) #I get the root category children_categories = root_category.get_descendants(include_self=False) #I get children in the root category category_list = [] # list for saving to base for data_category in data_categories: data_category = data_category.text try: cildren_cat = children_categories.filter(slug__icontains=data_category) category_list.append(cildren_cat) except Exception as ex: print(ex) category_list.append(root_category) category_list = list(set(category_list)) When creating a model: try: data = Post.objects.get(title=title) print('File duplicated in database!') data.save() except Post.DoesNotExist: print('File starting save in database!') data = Post.objects.create( title=title, slug=slug, content=format_html(content), created_by_id=7, is_published=True, author=', '.join(map(str, author_list)), source=self.task.url ) data.category.add(*category_list) data.save() I am catching a mistake: Task modules.parser.tasks.parser_driver_task[da70b753-fd59-4103-a32d-806096b52616] raised unexpected: TypeError("Field 'id' expected a number but got <TreeQuerySet []>.") I understand what the mistake is. But I don’t know how to solve another problem in order to get the root category and match its child categories and get the list of id as a result? Thanks for the help. -
Javascript - how to display the list of items based on the user in the search box
I have a django web page where user can registered and below there is a table, which display the list of users from the database in the table. I have created a search box when user types the username, that particular username should reflect in the table.I'm trying this with Js script I'm not much proficient in js.I have tried but i couldn't able to get it. html: search: <input type="text" id="myInput" placeholder="Search by name" class="form-control ng-pristine ng-valid ng-touched" onkeyup="myFunction()"> table: <table class="table table-striped table-hover table-responsive-lg"> <thead> <tr> <th> <a class="text-nowrap" style="cursor: pointer;"> Username </a> <th> <a class="text-nowrap" style="cursor: pointer;"> Email </a> </th> <th> <a class="text-nowrap" style="cursor: pointer;"> Address<span aria-hidden="true" class="cil-arrow-top"></span> </a> </th> <th> <a class="text-nowrap" style="cursor: pointer;"> Phone </a> </th> <th> <a class="text-nowrap" style="cursor: pointer;"> Action</a> </th> </tr> </thead> {% for list in userb %} <tbody> <tr id="myUL"> <td id='tdusername'>{{list.username }}</td> <td id='tdemail'>{{list.email }} </td> <td id='tdmy_date'>{{list.address}}</td> <td id='tdtimezone'>{{list.phone}}</td> <td><a style="text-decoration:none" href="{% url 'app:home' list.slug %}" id="btn-link" class="btn btn-sm btn-secondary">Edit</a> </td> </tr> </tbody> </div> </div> {% endfor %} {% endif %} js part: <script> function myFunction() { input = document.getElementById("myInput"); ul = document.getElementById("myUL"); console.log(ul.textContent) li = ul.getElementsByTagName("td"); console.log(li.textContent) for (i = 0; i < li.length; i++) { a = … -
Send form and object in ajax
I'm trying to send a form an a javascript object in an ajax call like so: $("#formTabla").submit(function(event){ event.preventDefault(); var formData = new FormData(this); $.ajax({ url : "{% url 'submit' %}", type: "POST", processData: false, contentType: false, data: { "checkboxes": formData, "datos": data } }); }); But all I'm getting as output is [object Object]. What am I doing wrong? -
ENV variable in docker environment
Hello how can I use env variable in Docker / docker-compose in the most convenient way? I am working with Django and in local environment I have something like this which works perfect - stripe.api_key = os.environ.get('stripeAPI') What should I do to do it in Docker container? When I wrote docker exec -e stripeAPI=(secret key) <container_id>I got an error command not found, but when I wrote at the end echo or bash I get into shell but Stripe does not work. -
Django Multiprocessing: How can I run multiple processes simultaneously
I am using a multiprocessing module to perform a task that is very time-consuming. With a single request, it works fine. but I am unable to generate multiple processes simultaneously. So How can I perform multiple requests at the same time when other is already running. -
python django framewExpected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
def post(self,request): try: profile_image=request.FILES['profile_image'] except: profile_image="" full_name=request.data.get('full_image') email=request.data.get('email') mobile_number=request.data.get('mobile_number') gender=request.data.get('gender') print(is_alcoholic) dob=request.data.get('dob') country=request.data.get('country') state=request.data.get('state') city=request.data.get('city') -
cURL POST Request - Ralph3 API (django)
i have the following problem, I’m trying to create a new VM in Ralph3 (inventory) via the API with the followed cURL command. However, i get the message “{” hypervisor “: [” This field is required. “]... It looks to me as if he is not accepting the values. Apparently it's because of my formatting Command: curl -X POST https://api.example.de/api/virtual-servers/ -H ‘Authorization: Token XXXXXXXXXXXXX’ -H ‘Content-Type: application/json’ -d ‘{“hostname”:“test”, “hypervisor”:{“url”:“http://api.example.de/api/data-center-assets/3/”}, “status”: “in use”}’ Tried: In addition, I tried to specify the url/ui_url with [, ] and {, } as a sub-section for the hypervisior information, without success. 1.) “hypervisor”:{“url”:“http://api.example.de/api/data-center-assets/3/”} 2.) “hypervisor”:[“url”:“http://api.example.de/api/data-center-assets/3/”] GET-Result if i used a GET-Request for informations about a System, i got this values for hypervisor. "hypervisor": { "url": "http://api.example.de/api/data-center-assets/9/", "ui_url": "http://api.example.de/r/11/9/" Can someone help me with this little difficulty? -
Annotate name without using annotate in view
I am building a BlogApp and I am trying to sort in list every thing is working fine, But when I add another list in sorting then i noticed that sorting was working with annotate name but in third query list I don't want to use any annotate so I cannot use annotate query name so it is not sorting the list according to date. views.py def page(request): query_1 = list(BlogPost.objects.filter(user=request.user).annotate(counting=Count('blog_likes')).order_by('-date'))[:2] query_2 = list(Comments.objects.filter(commenter=request.user).annotate(counting=Count('comment_likes')).order_by('-date_added'))[:2] # THIRD QUERY - which is causing error (Not really an error). I am not using annotate and i am # ordering through date query_3 = list(ThirdModel.objects.filter(user=request.user).order_by('date_created')) result_list = sorted(chain(query_1, query_2,query_3),key=attrgetter('counting')) context = {'result_list':result_list} return render(request, 'page.html', context) When i add the query_3 in sorted to sort the list then it is showing 'ThirdModel' object has no attribute 'counting' So I think it is is sorting third query according to below to two queries But I have no idea how can I name third query counting without annotate. Any help would be much Appreciated. Thank You -
select filtering and removal if they are already present in the db
look at the picture before answering me. that group2 is inside saved in the db with the button I open a modal that allows me to save other groups in the db and I would like that the same groups no longer appear in that select if I have already added them -
Django AttributeError with object
I want to display my product the front page this is the error I'm getting I can't figure out how to solve this. I can give you model of product and vendor. Thanks in advance. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/vendor/vendor-admin/ Django Version: 3.2.8 Python Version: 3.9.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.core', 'apps.product', 'apps.vendor'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Saad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Saad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Saad\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Saad\Desktop\fypm-c\mastercrafter\apps\vendor\views.py", line 30, in vendor_admin products = vendor.products.all(Vendor) Exception Type: AttributeError at /vendor/vendor-admin/ Exception Value: 'Vendor' object has no attribute 'products' -
ModelViewSet does not provide `create` url in Django Rest Framework
I have a viewset as below: class EntryViewSet(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class = EntrySerializer permission_classes = [permissions.IsOwnerStaffOrReadOnly] filter_backends = [DjangoFilterBackend, CustomOrderingFilter] filterset_class = EntryFilterSet ordering_fields = ["created_at", "last_update"] ordering = "created_at" @method_decorator(cache_page(60 * 5, key_prefix="entry")) def list(self, *args, **kwargs): return super().list(*args, **kwargs) @method_decorator(cache_page(60 * 60, key_prefix="entry")) def retrieve(self, *args, **kwargs): return super().retrieve(*args, **kwargs) ...which is added to urls.py of the related app using DefaultRouter as: _router.register("entries", EntryViewSet, basename="entry") However, doing reverse("api:entry-create") fails to find create on my test. I also quickly check the URLs with Django Extensions subcommand show_urls but it does not print api:entry-create, which means it is not registered. What I do: python manage.py show_urls | grep "api:entry" The result is: /api/entries/ api.viewsets.entry.EntryViewSet api:entry-list /api/entries/<pk>/ api.viewsets.entry.EntryViewSet api:entry-detail /api/entries/<pk>\.<format>/ api.viewsets.entry.EntryViewSet api:entry-detail /api/entries\.<format>/ api.viewsets.entry.EntryViewSet api:entry-list ...which shows only entry-detail and entry-list are registered while my model clearly is not ReadOnlyModelViewSet. Why do I not have api:entry-create url? Environment django ^2.2 djangorestframework ^3.12.4 -
django nginx not serving static files
I am depploying django using nginx and gunicorn. When I access the website I get the following errors. open() "/home/x/aroundu/core/static/static/rest_framework/js/default.js" failed it's accessing static files wrong, because the path should be like this open() "/home/x/aroundu/core/core/static/rest_framework/js/default.js" failed server { listen 80; location /static/ { alias /home/x/aroundu/core/core/static/; } location /media/ { alias /home/x/aroundu/core/media/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = "/media/" -
Can't read session data from database
I have inherited a legacy django application (currently on 2.2.24), that I am trying to modernize step by step. One requirement is to move from MySQL to an Azure SQL database. Unfortunately, I ran into an issue, where I just can't read back the session data from the database. This is what my settings.py looks like. As you can see, django.contrib.sessions is set, as well as django.contrib.sessions.middleware.SessionMiddleware. Also, I have explicitly set SESSION_ENGINE = 'django.contrib.sessions.backends.db', which should be the default. # ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_swagger', # ... ] 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', 'simple_history.middleware.HistoryRequestMiddleware', ] SESSION_ENGINE = 'django.contrib.sessions.backends.db' ] DATABASES = { 'default': { 'ENGINE': 'mssql', # https://github.com/microsoft/mssql-django 'NAME': '<hiden>', 'USER': '<hiden>', 'PASSWORD': '<hiden>', 'HOST': '<hiden>', 'PORT': '1433, 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', } } } # ... This is what the misbehaving views.py looks like, which is part of an Azure AD login procedure (def auth(request) => sso/login & def complete(request) => sso/complete) After execution leaves def auth(request), I can see a new entry in the table dbo.django_session. However, when execution enters def complete(request), the session dictionary is empty. @never_cache def auth(request): …