Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
heroku failing to process requirements.txt "because these package versions have conflicting dependencies."
I have pushed this project many times before and have made no changes to the requirements.txt file located in the root directory of the project, however. Heroku will no longer accept the same requirements.txt file citing a dependency issue Heroku still opens the last valid push to allow me to "pip freeze" pushed heroku requirements.txt appnope==0.1.2 asgiref==3.4.1 backcall==0.2.0 backports.entry-points-selectable==1.1.0 blis==0.7.4 catalogue==2.0.6 certifi==2021.5.30 charset-normalizer==2.0.4 ChatterBot==1.0.4 chatterbot-corpus==1.2.0 click==8.0.1 colorgram.py==1.2.0 cymem==2.0.5 debugpy==1.4.3 decorator==5.1.0 distlib==0.3.3 dj-database-url==0.5.0 Django==3.2.8 django-filter==2.4.0 django-heroku==0.0.0 django-simple-chatbot==0.0.9 django-widget-tweaks==1.4.8 djangorestframework==3.12.4 en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.1.0/en_core_web_sm-3.1.0-py3-none-any.whl entrypoints==0.3 filelock==3.3.0 future==0.18.2 greenlet==1.1.2 gunicorn==20.1.0 heroku==0.1.4 httpie==2.4.0 huggingface-hub==0.0.12 idna==3.2 ipykernel==6.4.1 ipython==7.28.0 ipython-genutils==0.2.0 jedi==0.18.0 Jinja2==3.0.1 joblib==1.0.1 jupyter-client==7.0.3 jupyter-core==4.8.1 line-bot-sdk==1.20.0 MarkupSafe==2.0.1 mathparse==0.1.2 matplotlib-inline==0.1.3 murmurhash==1.0.5 nest-asyncio==1.5.1 nltk==3.6.2 numpy==1.21.2 packaging==21.0 parso==0.8.2 pathy==0.6.0 pexpect==4.8.0 pickleshare==0.7.5 Pillow==8.3.2 Pint==0.17 pipenv==2021.5.29 platformdirs==2.4.0 preshed==3.0.5 print==1.3.0 prompt-toolkit==3.0.20 psycopg==3.0b1 psycopg2==2.9.1 psycopg2-binary==2.9.1 ptyprocess==0.7.0 pydantic==1.8.2 Pygments==2.10.0 pymongo==3.12.0 pyparsing==2.4.7 PySocks==1.7.1 python-dateutil==2.7.5 pytz==2021.3 PyYAML==5.4.1 pyzmq==22.3.0 regex==2021.8.28 requests==2.26.0 requests-toolbelt==0.9.1 sacremoses==0.0.46 six==1.16.0 smart-open==5.2.1 spacy==3.1.3 spacy-alignments==0.8.3 spacy-legacy==3.0.8 spacy-transformers==1.0.6 SQLAlchemy==1.2.19 sqlparse==0.4.2 srsly==2.4.1 textblob==0.15.3 thinc==8.0.10 tokenizers==0.10.3 torch==1.8.1+cpu torchvision==0.9.1+cpu tornado==6.1 tqdm==4.62.2 traitlets==5.1.0 transformers==4.9.2 turtle==0.0.1 typer==0.4.0 typing-extensions==3.10.0.2 urllib3==1.26.6 virtualenv==20.8.1 virtualenv-clone==0.5.7 wasabi==0.8.2 heroku now tells me the following error when i try to deploy my latest version using identical requirements.txt files. The conflict is caused by: The user requested PyYAML==5.4.1 chatterbot-corpus 1.2.0 depends on PyYAML<4.0 and >=3.12 To fix this you could … -
Error when pip installing Django-Sass-Processor
I get the following error when running the code: pip install libsass django-compressor django-sass-processor Here is the error: ERROR: Command errored out with exit status 1: command: 'c:\users\jsooh\appdata\local\programs\python\python39\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\jsooh\\AppData\\Local\\Temp\\pip-install-htugdym8\\rcssmin_25699a9d5e6f4f74bfe031fe694d8529\\setup.py'"'"'; __file__='"'"'C:\\Users\\jsooh\\AppData\\Local\\Temp\\pip-install-htugdym8\\rcssmin_25699a9d5e6f4f74bfe031fe694d8529\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\jsooh\AppData\Local\Temp\pip-record-0h133shl\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\jsooh\appdata\local\programs\python\python39\Include\rcssmin' cwd: C:\Users\jsooh\AppData\Local\Temp\pip-install-htugdym8\rcssmin_25699a9d5e6f4f74bfe031fe694d8529\ Complete output (9 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.9 copying .\rcssmin.py -> build\lib.win-amd64-3.9 running build_ext building '_rcssmin' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\jsooh\appdata\local\programs\python\python39\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\jsooh\\AppData\\Local\\Temp\\pip-install-htugdym8\\rcssmin_25699a9d5e6f4f74bfe031fe694d8529\\setup.py'"'"'; __file__='"'"'C:\\Users\\jsooh\\AppData\\Local\\Temp\\pip-install-htugdym8\\rcssmin_25699a9d5e6f4f74bfe031fe694d8529\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\jsooh\AppData\Local\Temp\pip-record-0h133shl\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\jsooh\appdata\local\programs\python\python39\Include\rcssmin' Check the logs for full command output. Does anyone know how to fix this? Thanks, and please let me know if you have any questions. -
Calendar lost formatting after adding bootstrap
My site is used to add and delete items on and from the calendar, my site looked like this at first then when I added the bootstrap libraries, my calendar lost the formatting and the checkbox to delete items disappeared: enter image description here enter image description here -
How to get the entity after form.save()
I have form class which receive the POST request from web browswer. class WaveFileForm(forms.ModelForm): class Meta: model = WaveFile fields = ('description', 'document', ) then it will be saved as model entity by form.save() if request.method == 'POST': form = WaveFileForm(request.POST, request.FILES) if form.is_valid(): form.save() print(form.cleaned_data.get('document'))// it returns filename, but I want to have saved file path, so I want entity itself WaveFile.objects.get("(saved_one)") But now I want to get the entity immediatelly it self which is saved by form.save() How can I do this?? -
'datetime.date' object has no attribute 'tzinfo'
I don't have any date type field neither in my model nor in the database. What is the reason to get this error? enter image description here enter image description here enter image description here -
Django: automatically save foreign key fields
I'm trying to populate automatically my foreign key field when my form is submitted. I successeffuly set the user field but I have trouble with form.instance.staff and form.instance.event since I'm getting error like 'User' object has no attribute 'staffduty' . I'd also like to pass and save some variables like the date_appointment and the event name but I don't know how to do so. Thanks for your help models.py class Event(models.Model): name = models.CharField(max_length=255) staff_needed = models.PositiveIntegerField() date = models.DateField() def __str__(self): return self.name def get_absolute_url(self): return reverse('event_details', args=[str(self.id)]) class StaffDuty(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) date_work = models.DateField() shift = models.CharField(max_length=255) def __str__(self): return self.event.name | str(self.date_work) class UserAppointment(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) staff = models.ForeignKey(StaffDuty, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) event_name = models.CharField(max_length=255) date_appointment = models.DateField(null=True) def __str__(self): return self.event.name | str(self.staff.date_work) def get_absolute_url(self): return reverse('home') views.py class StaffDutyAddView(CreateView): model = StaffDuty form_class = StaffDutyForm template_name = 'reservation.html' success_url = reverse_lazy('home') class UserAppointmentAddView(CreateView): model = UserAppointment form_class = UserAppointmentForm template_name = "reservation.html" def form_valid(self, form): form.instance.user = self.request.user.userinformation form.instance.staff = StaffDuty.objects.filter(user=self.request.user.staffduty).first() #form.instance.date_appointment = # add date_work from StaffDuty class form.instance.event = Event.objects.filter(user=self.request.user.event).first() #form.instance.event_name = # add name of the event from Event class return super(UserAppointmentAddView, … -
How to get a value of foreign key between apps of Django?
Need a little bit of help :) I have two apps (accounts and company). accounts/models.py class Organization(models.Model): organization_name = models.CharField(max_length=20) #custom user model class NewUser(AbstractBaseUser): which_organization = models.ForeignKey(Organization, on_delete = models.CASCADE, null=True, blank=True) #other fields company/models.py from accounts import models as accounts_model class Branch(models.Model): branch_name = models.ForeignKey( accounts_model.Organization, on_delete = models.CASCADE, null=True, blank=True) #other fields company/forms.py from .models import Branch class BranchForm(forms.ModelForm): class Meta: model = Branch fields = '__all__' company/views.py from .forms import BranchForm def some_function(request): form = BranchForm() if request.method == 'POST': form = BranchForm(request.POST, request.FILES) if form.is_valid(): form.save(commit=False) form.branch_name = request.user.which_organization print("User organization: ", request.user.which_organization) form.save() return render(request, 'company/index.html', {'form': form}) P.s. Everything works well. I am able to print the user's organization with print("User organization : ", request.user.which_organization) But cannot save it with form.branch_name = request.user.which_organization in views.py. Instead of getting exact organization name of the user, created object lists all organization names... How to achieve it?) -
Django KeyError at /manhattan/{% url 'activity' }
I was given the task to create an NYC Guide project out of Python and Django. I am iterating through a nested dictionary to render boroughs, activities, and venues. The home page lists a handful of boroughs. The boroughs page lists a handful of activities in each borough. The activities page lists a handful of venues to select. My issue is when I click on one of the venues I get a keyerror. I am trying to at least render the venues page that has a simple 'VENUES PAGE' on it. I'd love any advice or feedback. This is my first Django project so forgive me if I didn't explain this thoroughly enough. Feel free to ask for further explanation! What I am ultimately trying to do is create a url that takes me to the venue.html page. It doesn't have to render a specific venue. I can take it from there. I am stuck on this one step. //Here is my boroughs.py `boroughs = { 'brooklyn': { 'beaches': { 'brighton beach': { 'img_link': '', 'description': 'Also known as "Little Odessa" due its tight-knit Russian and Eastern European communities, Brooklyn\'s Brighton Beach is a lively neighborhood with many high-rise residential … -
Django for loop to display all objects in database
def homepage(response): data = Project_types.objects.all() return render(response, 'main/homepage.html',{'projects':data}) def hacks(response): return render(response, 'main/hacks.html', {}) def games(response): return render(response, 'main/games.html', {}) All I need to know is how to iterate through each object in the variable "data" in html. I want it displayed in the most simple way possible ! -
Why this loop doesn't work correctly? Python, Selenium
So im building an Django API, and im trying to put a bunch of information through Selenium, i have a JSON file that i converted to an Excell file and using xlrd, i read it and i want to put the data in Django like this : for curr_row in range(1, sheet.nrows): titlevalue = sheet.cell_value (curr_row, 0) descriptionvalue = sheet.cell_value(curr_row, 2) imagevalue = sheet.cell_value (curr_row, 1) keywordsvalue = sheet.cell_value (curr_row, 3) title.send_keys(titlevalue) description.send_keys(descriptionvalue) image.clear() image.send_keys(imagevalue) keywords.send_keys(keywordsvalue) save.click() addarticle.click() This loop in my mind it should do it, like post an article after article with the data from the Excell file, but it only work once, it writes the first article with the first row and then it stops, it doesn't run again, why? -
Getting Data from the Frontend & CORS
i´m stuck at a little demo project from udemy with django and api calls. I have this in main.js and I want to get array of object and not just a json list in console. let projectsUrl = 'http://127.0.0.1:8000/api/projects/' let getProjects = () => { fetch(projectsUrl) .then(response => response.json()) .then(data => { console.log(data) buildProjects(data) }) } let buildProjects = (projects) => { let projectsWrapper = document.getElementById('testz') for (let i = 0; projects.lenght > i; i++){ let project = projects[i] console.log(project) } } getProjects() The result : Console Log and the result should be something like this : Console Log -
How can I access to data stored in a ManyToMany related table in Django?
I want to make a query to obtain all the users that another user is "following" for a learning project. When I execute the following python code: user = User.objects.get(id=user_id) followers = user.follows.all() I don't get an error but instead I get a list with an object ( called Follow object (4) ) from wich I can't access the user related properties. I've checked this documentation here: https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/ But I can't find where I'm falling to use properly this type of model-relation. Here are my Django models: class User(AbstractUser): pass class Follow(models.Model): user = models.ForeignKey(User, null=False, on_delete=models.CASCADE, related_name="follows") follow = models.ManyToManyField(User, blank=True, related_name="followed_by") I searched in my Django DB to see what is happening and I saw that there is a relational table called "network_follow_follow" that in fact has all the info that I need and is related with the object that I get from my Query, here are two pictures about the table that I can access and the one that I don't know how to access: Table data requested by my code Table that I need to query So now I'm looking a way to access that last table, but to know how can I access straight forward … -
Getting HTTP 405 Method error on POST view
I'm working with the Django rest framework and I'm getting this error when I'm trying to make a post view. HTTP 405 Method Not Allowed Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Method \"GET\" not allowed." } my API view @api_view(['POST']) def createroom(request): account = User.objects.get(pk=1) account2 = Topic.objects.get(pk=2) create_room = Room(host=account, topic=account2) if request.method == "POST": serializer = RoomSerializer(create_room, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_401_BAD_REQUEST) This is my model class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(User, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name and the serializer class RoomSerializer(ModelSerializer): class Meta: model = Room fields = '__all__' It's saying that "GET" is not allowed but I'm making a POST view. How can I fix this? -
Storing a matrix in django model
I would like to store a matrix (from a file) in django and upload it to sqlite. I have seen that some people advise to store it per cells, but as it is a huge matrix (more than a thousand elements) I wouldn't like to store it that way, but as a whole. I am thinking about storing it as a list, but it is also not easy, because the elements are floats. Is there a simple/doable way to store my matrix? view.py new_file = [[8.2, 14.2, -6.1], [12.6,7.0,4.7], [-1.1,3.6,21.1]] def file_list(request): content = new_file[:] content = chain.from_iterable(zip(*content)) extract_data = Cell(content = content) extract_data.save() model.py class Cell(models.Model): content = models.FloatField() #ok, obviously this doesn't work -
Django template tag if/else/endif always goes to "else"
I need some help to figure out where is a problem. For example i have similar code: views.py context = { 'Tru': 1 == 1, 'perm': {} } context['perm']['can_do'] = some_var == 1 context['perm']['also_can'] = another_var == True template.html {% if perm.can_do or perm.also_can or perm.can_do is True or perm.can_do == 1 or perm.can_do == Tru %} PASS {% else %} {{ perm.can_do }} {{ perm.can_do|typeof }} {% endif %} But when page is rendered i see True <class 'bool'> instead of PASS. Is there something wrong with Django or i miss something? Btw, Django 3.2 and Python 3.10 if it matter. -
How do I use the ModelSerializer with the ListSerializer in Django Rest Framwork?
I want to be able to send POST requests which include lists of the location model. The reason for this is that I want to send the sensor data periodically. I have tried the following but end up with this error. How should I implement the create method and am I doing this the correct way? raise NotImplementedError('`create()` must be implemented.') NotImplementedError: `create()` must be implemented. serializers.py class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ['latitude'] class MultiLocationSerializer(serializers.Serializer): items = LocationSerializer(many=True) views.py class LocationViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Location.objects.all() serializer_class = MultiLocationSerializer permission_classes = [permissions.IsAuthenticated] urls.py router = routers.DefaultRouter() router.register(r'locations', ph.BookViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] -
How to make django-crontab execute commands in Docker container?
In order to periodically execute tasks in my Django app I have installed django_crontab extension. https://pypi.org/project/django-crontab/ I have done every step as it is described in setup paragraph. settings.py INSTALLED_APPS = [ ... 'django_crontab', ] ... CRONJOBS = [ ('*/1 * * * *', 'config.cron.fun') ] cron.py def fun(): print("hello cron") with open("./test.txt", "a") as f: f.write("Hello") I also add cron job in docker-entrypoint.yml: python manage.py crontab add python manage.py crontab show In Dockerfile I use python:3.8 image and install cron: RUN apt-get install -y cron && touch /var/log/cron.log And no response after running the container. When I enter the container, I can see that cron sees the job, but still does not execute it. root@bar:/back# crontab -l */1 * * * * /usr/local/bin/python /back/manage.py crontab run ebcca28ea3199afe6d09a445db5d5fd8 # django-cronjobs for config How can I fix it? -
How can I include in the JSON's GET request the list of foreign keys of a model in Django?
My models have users that can have multiple devices. When I do a GET request on users it returns only the fields specified in the user model, as it should. But I want the option to include in the JSON returned by the GET request the list of devices the user has. How can I do that? It would be nice to specify in the query string a boolean or something in order do specify if I want the user's JSON to have or not the list of devices. But this is just my ideea, maybe it could be done diffrently and better. Also, I am really new to Django, and I would appreciate a lot code examples to understand better, if possible. These are my models: class User(models.Model): name = models.CharField(max_length=100) birth_date = models.DateField() address = models.CharField(max_length=200) class Device(models.Model): description = models.CharField(max_length=200) location = models.CharField(max_length=200) max_energy_consumption = models.FloatField() avg_energy_consuumption = models.FloatField() user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) My serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class DeviceSerializer(serializers.ModelSerializer): class Meta: model = Device fields = '__all__' And the following default ModelViewSets for CRUD api calls: class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class DeviceViewSet(ModelViewSet): queryset = … -
Djongo (not django, djongo): pymongo.errors.ServerSelectionTimeoutError: cluster0 [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:
I have a simple web application and I need to connect to my mongodb instance so I can perform basic queries and also update the database. I have djongo and pymongo[srv] installed. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'strands', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': "mongodb+srv://db-admin:"+ PASS + CLUSTER } } } -
How to add a field with POST using Fetch API in Django app?
Hello I am trying to use the fetch api to call the POST request and create/add a new item to the table using vue. I am not sure where and how to create a form to input details. I have this code until now: I already have delete and edit functions working, I just need the POST one. countries.html <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Country</th> <th scope="col">Code</th> <th width="100" scope="col"></th> </tr> </thead> <tbody> <tr v-for="(country, index) in countries"> <th scope="row"> [[ index ]] </th> <td> <input v-if="country.editing" type="text" v-model="country.name" /> <a v-else :href="country.url"> [[ country.name ]] </a> </td> <td> <input v-if="country.editing" type="text" v-model="country.code" /> <span v-else>[[ country.code ]]</span> </td> <td class="d-flex justify-content-between"> <button v-if="!country.editing" @click="country.editing = true" class="btn btn-sm btn-secondary"> Edit </button> <button v-else @click="saveCountryChanges(country)" class="btn btn-sm btn-success"> Save </button> <button @click="deleteCountry(country)" class="btn btn-sm btn-danger"> Delete </button> </td> </tr> </tbody> </table> <script> methods: { async addCountry(country) { let response = await fetch(country.api, { method: "POST", body: JSON.stringify({ name: country.name, code: country.code, }), headers: { "Content-Type": "application/json", "X-CSRFToken": document.querySelector("[name=csrfmiddlewaretoken").value, } }); if (response.ok) { country.adding = false; } else { // country add failed alert("Failed to add changes"); } } </script> api.py def country_api(request, country_id): country = get_object_or_404(Country, id=country_id) … -
azure static files missing/ wrong MIME
Django website deployed to Azure (F1 - free subscription) Linux, all static files are missing/ not rendered. Even the files from admin which are not changed. Locally works fine, I've googled around tried to upload without VS code etc. still does not work. Source code of app - https://github.com/Azure-Samples/python-docs-hello-django Tutorial - https://docs.microsoft.com/en-us/azure/app-service/quickstart-python?tabs=bash&pivots=python-framework-django Deployed via Azure CLI, any pointers I would gladly take. -
Page not found - The current path, matched the last one
I have created an update view. I want to add a button to the post that directs to the update view. However when you click the button you get this error. 404 Page not found post/<int:pks>/build-log/<int:pk>/update/ [name='build-log-update'] post/75/build-log/127/update/, matched the last one.` The reason for this error occurring is because it is flipping the PK when you click the button. Example. /post/127/build-log/75/ after button clicked /post/75/build-log/127/update/ you can see it is flipping the PK. If just just append update to the good url it works fine I cannot figure out why it is flipping the pks html: <a class="delete-btn" href='{% url "build-log-delete" pk=log.post_id pkz=log.pk %}'>Delete</a> <a class="update-btn" href='{% url "build-log-update" pk=log.post_id pkz=log.pk %}'>Update</a> urls: path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'), path('post/<int:pk>/build-log/<int:pkz>/delete/', views.BuildLogDelete, name='build-log-delete'), path('post/<int:pks>/build-log/<int:pk>/update/', UpdateBuildLog.as_view(), name='build-log-update') model: class BuildLog(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey('Post', on_delete=models.CASCADE) def get_absolute_url(self): return reverse('build-log-view', kwargs={'pkz': self.pk}) view: class UpdateBuildLog(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = BuildLog form_class = BuildLogupdateForm template = 'blog/buildlog_update.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user.id == post.author_id: return True return False -
How to combine 2 queries in Postgresql?
I face with a problem, I have 2 selects and I need to combine them into one output? I want to get one select table with column shop.name, COUNT("Fins_shop"."name") as count_goods MAX("Fins_price"."price") as max_price, Count("Fins_shop"."name") as count_department, SUM("Fins_department"."staff_amount"), first select SELECT "Fins_shop"."name", COUNT("Fins_shop"."name") as count_goods MAX("Fins_price"."price") as max_price FROM "Fins_shop" INNER JOIN "Fins_department" ON "Fins_department"."shop_id" = "Fins_shop"."id" INNER JOIN "Fins_item" ON "Fins_item"."department_id" = "Fins_department"."id" GROUP BY "Fins_shop"."name" second select SELECT "Fins_shop"."name" , Count("Fins_shop"."name") as count_department, SUM("Fins_department"."staff_amount"), FROM "Fins_shop" INNER JOIN "Fins_department" ON "Fins_department"."shop_id" = "Fins_shop"."id" GROUP BY "Fins_shop"."name" if table table has foreign key to department and table department has foreign key to shop Also have models of this tables: class Shop(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=200) staff_amount = models.PositiveIntegerField(default=0) def __str__(self): return f'{self.id}{self.name} with staff {self.staff_amount}' class Meta: verbose_name = 'Shop' verbose_name_plural = 'Shops' ordering = ['id'] def get_absolute_url(self): return reverse('shop_detail', kwargs={'pk': self.pk}) class Department(models.Model): sphere = models.CharField(max_length=200) staff_amount = models.PositiveIntegerField(default=0) shop = models.ForeignKey( Shop, on_delete=models.CASCADE, related_name='department_relate', related_query_name='department_filter', ) def __str__(self): return f'{self.id}-{self.sphere}-{self.shop}' class Meta: verbose_name = 'Department' verbose_name_plural = 'Departments' ordering = ['id'] def get_absolute_url(self): return reverse('department_detail', kwargs={ 'shop_pk': self.shop.id, 'pk': self.id}) class Item(models.Model): name = models.CharField(max_length=200) description = models.TextField() price = models.PositiveIntegerField(default=0) is_sold = models.BooleanField(default=False) comments … -
django-rest-auth with allauth customuser TypeError: 'PhoneNumber' object is not subscriptable
models.py class CustomUser(AbstractUser): username = PhoneNumberField(unique=True) payloads: { "username": "+8801700000000", "password1": "demo", "password2": "demo", "email": "demo@demo.com", } response: Internal Server Error: /api/rest-auth/registration/ Traceback (most recent call last): File "venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "venv\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "venv\lib\site-packages\rest_auth\registration\views.py", line 46, in dispatch return super(RegisterView, self).dispatch(*args, **kwargs) File "venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "venv\lib\site-packages\rest_framework\generics.py", line 190, in post return self.create(request, *args, **kwargs) File "venv\lib\site-packages\rest_auth\registration\views.py", line 65, in create user = self.perform_create(serializer) File "venv\lib\site-packages\rest_auth\registration\views.py", line 73, in perform_create user = serializer.save(self.request) File "venv\lib\site-packages\rest_auth\registration\serializers.py", line 210, in save adapter.save_user(request, user, self) File "venv\lib\site-packages\allauth\account\adapter.py", line 242, in save_user self.populate_username(request, user) File "venv\lib\site-packages\allauth\account\adapter.py", line 209, in populate_username user_username( File "venv\lib\site-packages\allauth\account\utils.py", line 120, in user_username return user_field(user, app_settings.USER_MODEL_USERNAME_FIELD, *args) File "venv\lib\site-packages\allauth\account\utils.py", line 110, in user_field v = … -
Group by in and nesting result in Django Rest Framework
im working in an API and i want to order by id DESC but i want to group by client_id too, so i could have all the questions from same clients ordered, nesting the results: This is my code: models.py class QuestionsModel(models.Model): id = models.IntegerField() publication_id = models.IntegerField(blank=True, null=True) publication_title = models.CharField(max_length=255) publication_link = models.CharField(max_length=255) question = models.CharField(max_length=255) member_id = models.IntegerField() client_id = models.IntegerField() class Meta: managed = False db_table = 'questions' serializers.py class QuestionsSerializer(serializers.ModelSerializer): class Meta: model = QuestionsModel fields = '__all__' views.py class QuestionsAPIView(generics.ListAPIView): def get_queryset(self): queryset = '' member_id = self.request.query_params.get('member_id') if member_id is not None and member_id.isnumeric(): queryset = QuestionsModel.objects.filter(member_id=member_id).order_by('-id') return queryset Result: { "id": 848484, "publication_id": 4444, "publication_title": "Title publication", "publication_link": "Link", "question": "This is a test question", "member_id": 123456, "client_id": 500 } What i want: Group questions by client_id, so desire output JSON could be: { "client_id": 500, "question" : [ "id": 848484, "publication_id": 4444, "publication_title": "Title publication", "publication_link": "Link", "question": "This is a test question", "member_id": 123456, "client_id": 500 ], [ "id": 848485, "publication_id": 4445, "publication_title": "Title publication", "publication_link": "Link", "question": "This is a test question", "member_id": 123456, "client_id": 500 ] } Notes: I'm using SQL Server as db engine.