Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.ProgrammingError: relation "#" does not exist
Hi I made some changes to my Django app, and migrating them gives the error message-- django.db.utils.ProgrammingError: relation "#" does not exist Changing my database server works, but I have a lot of data on my original server which I can't lose. Is there any way around it? I have been on this for hours without any solution. -
Is there a way to disable throttling while using Pytest in Django?
Problem: I want to figure out a way to disable throttling when running my tests with pytest -vv Details: I have this default throttling policy in my settings.py file: 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '1000/day' } I also have this fixture in my confest.py which returns an error whenever I exceed the limit of requests: def get_token(user, client): response = client.post( "/email-login", {"email":user.email, "password": "B9vX95phJDi3C4"}, ) return { "HTTP_AUTHORIZATION": f"Bearer {response.json()['token']['access']}" } What I have tried: I have attempted to use the solution in this GitHub Issue: https://github.com/encode/django-rest-framework/issues/1336, but it doesn't work in my case. -
Javascript/Django: change icon on dynamically created element based on query value or click
I have tried couple of ways to get icon to change on a button, that has been created with for loop on page load. Here is my element: {% for i in data %} <div class="accordion"> <div style="margin-left: -10px;"> <a href="#collapse{{ i }}", class="btn", role="button", data-bs-toggle="collapse" id="btn-collapse_{{ i }}"> <i class="material-icons" style="vertical-align: middle;">expand_more</i> <label style="vertical-align: middle;">{{ i }}</label> </a> </div> </div> {% endfor %} Here is my function to change the icon: <script> $(document).ready(function(){ $('#btn-collapse_{{ i }}').on('click', function () { var thisElement = $(this); var anchorElement = thisElement.find("i"); if(anchorElement.text() === "expand_less"){ anchorElement.text('expand_more'); } else { thisElement.find("i").text("expand_less"); } }); }); </script> I've also tried changing the color in in another instance. Heres the element: <tbody> {% for i in data %} <tr style="vertical-align: middle;"> <td><a href="#">{{ i }}</a></td> <td>{{ i.data1 }}</td> <td><a href="#">{{ i.data1 }}</a></td> <td style="text-align: center;"> <button class="btn", id="btn-{{ i.data2 }}"> <i class="far fa-check-circle"></i> </button> </td> <td style="text-align: center;"> <button class="btn", id="btn-{{ i.data3 }"> <i class="far fa-check-circle"></i> </button> </td> </tr> {% endfor %} </tbody> And here is the function: <script> $(document).ready(function(){ var data_button = document.getElementById("btn-{{ i.data2 }}"); if({{ i.data2 }} == 'None'){ data_button.style.color = "#858796"; } else { data_button.style.color = "#1cc88a"; } }); </script> Data that is being queried … -
Using foreignkey in a select form element pulls data but in the database it is null
I am building an app in Django. I have a couple of models as defined below id = HashidAutoField(primary_key=True, salt='ClientBgColor' + settings.HASHID_FIELD_SALT) color = models.CharField(max_length=10, blank=True, null=True) def __str__(self): return self.color class Client(models.Model): id = HashidAutoField(primary_key=True, salt='Client' + settings.HASHID_FIELD_SALT) company_name = models.CharField(max_length=100, blank=True, null=True) contact_name = models.CharField(max_length=100, blank=True, null=True) contact_email = models.EmailField(max_length=100, blank=True, null=True) phone = models.CharField(max_length=100, blank=True, null=True) address = models.CharField(max_length=100, blank=True, null=True) country = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) logo = models.ImageField(upload_to='clients/logo/', blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): template = '{0.company_name}' return template.format(self) class ProjectType(models.Model): id = HashidAutoField(primary_key=True, salt='ProjectType' + settings.HASHID_FIELD_SALT) name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): template = '{0.name}' return template.format(self) class Project(models.Model): id = HashidAutoField(primary_key=True, salt='Project' + settings.HASHID_FIELD_SALT) project_name = models.CharField(max_length=100, blank=True, null=True) client = models.ForeignKey('Client', on_delete=models.CASCADE, related_name='clientProjects') created_on = models.DateTimeField(auto_now_add=True) description = models.TextField(null=True, blank=True) project_type = models.ForeignKey('ProjectType', on_delete=models.CASCADE, related_name='typeOfProject', blank=True, null=True) last_updated = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.project_name in the forms.py file, from dataclasses import fields from django import forms from app.models import * class NewProjectForm(forms.ModelForm): project_name = forms.CharField( label = '', widget=forms.TextInput(attrs={ 'id' : '', 'class' : 'form-control form-control-lg', 'placeholder' : 'Project name' }) ) client = … -
Django: How to order by model field name, then by its reverse queryset's first entry and field?
I'm using Postgres as the db backend. I have a Load that has multiple Stops, which each Load assigned to a Carrier. Each Stop has an appointment through a DateTimeField. I'm trying to sort all Loads by Carrier's company_name, then by the Stop's appointment. Table to illustrate Shipment # | Carrier | 1st Appointment Time 10001 | ABC Freight | 01/01/2023 17:00 10002 | ABC Freight | 01/01/2023 20:00 90001 | XYZ Freight | 01/01/2023 08:00 90002 | XYZ Freight | 01/01/2023 11:00 First solution from the shell: from app.models import Load Load.objects.all().order_by('carrier__company_name', 'stops__appointment') Problem: It returns duplicate entries of the Loads queryset. When I try to add .distinct('id') the following error occurs SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("app_load"."id") "app_load"."id", "app_l... What query functions would I need to combine to get this result? models.py class Load(models.Model) shipment = models.CharField(max_length=100, blank=True) carrier = models.ForeignKey(Carrier, blank=True) class Carrier(models.Model): company_name = models.CharField(max_length=100) class Stop(models.Model): load = models.ForeignKey(Load, on_delete=models.CASCADE, related_name='stops') appointment = models.DateTimeField(blank=True, null=True) -
DRF's not calling post() method when receiving POST request
I have a viewset like this: class MyViewSet(CreateAPIView, RetrieveModelMixin, ListModelMixin, GenericViewSet): queryset = MyModel.objects.all() serializer_class = MySerializer def post(self, request, *args, **kwargs): import pdb; pdb.set_trace() class MySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyModel fields = ['id', 'field1', 'field2'] #only field1 is required in the model The GET requests for list, and retrieve works perfectly. When I make a POST request, sending the field1 I get a status 201 and a new record is added to the database, so it works too. But my method MyViewSet.post() that should overwrite the same one from generics.CreateAPIView never gets called. Not only that, but I've tried to add the pdb.set_trace(), literally inside the generics.CreateAPIView.post() and in the CreateModelMixin.create() functions and neither stopped once I made the POST request. So something else is handling this POST request and inserting into the DB, I just don't know what. And how can I overwrite it, so I can customize what should be done with a post request? PS.: Also, I don't think it's a routing problem, my urls.py: from rest_framework import routers from myapp.views import MyViewSet, AnotherViewSet router = routers.DefaultRouter() router.register(r'route_one', MyViewSet) router.register(r'route_two', AnotherViewSet) -
django error (no such column: projects_review.project_id)
i cant open my review table here's the models code class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) demo_link = models.CharField(max_length=2000, null=True, blank=True) source_link = models.CharField(max_length=2000, null=True, blank=True) tags = models.ManyToManyField('Tag', blank=True) vote_total = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title and this is the review model class Review(models.Model): VOTE_TYPE = ( ('up', 'Up Vote'), ('down', 'Down Vote'), ) project = models.ForeignKey(Project, on_delete=models.CASCADE) body = models.TextField(null=True, blank=True) value = models.CharField(max_length=200, choices=VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False) def __str__(self): return self.title but i cant open my review table on admin table (OperationalError at /admin/projects/review/) -
Is there a way to save an image using cv2.imwrite() function in django models?
I am trying to save the resized images from the views.py in django using opencv but I could not save the image from views.py. I want to generate images using cv2.imwrite() inside the views and save it directly from the views instead of saving it from django admin dashboard. Code to create image in views.py models.py -
Troubles with django ORM, when i filter a model instance, the filter apparently isn't work like have to be
My environment Django version = 4.0.4 Python == 3.9.12 os = osx I'm confused when I'm trying to make a filter on a model using a customized template tag in this way @register.filter def cart_item_count(user): if user.is_authenticated: qs = Order.objects.filter(user=user, ordered=False) print(qs.ordered) if qs.exists(): return qs[0].items.count() else: return 0 return 0 but even when i say in the filter that i just want the ordered=False, i make a print to ensure what value have my queryset and its prints to me True, why of this behavior? It's always returning to me a true ordered order, but I want to just take that have the ordered false, because I want to show in my cart an empty cart after making the checkout POST for redirect to home o other view and update for me to an empty new cart, pls if someone can help me even with an article post about it and explain to me what I'm doing wrong, thanks! -
Django Middleware: RecursionError when accessing `self.request.user` in database query wrapper
I'm testing my database query middleware (Django docs here) on a sample django app with a Postgres db. The app is the cookiecutter boilerplate. My goal with the middleware is simply to log the user ID for all database queries. Using Python3.9 and Django3.2.13. My middleware code is below: # Middleware code import logging import django from django.db import connection django_version = django.get_version() logger = logging.getLogger(__name__) class Logger: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): with connection.execute_wrapper(QueryWrapper(request)): return self.get_response(request) class QueryWrapper: def __init__(self, request): self.request = request def __call__(self, execute, sql, params, many, context): # print(self.request.user) return execute(sql, params, many, context) If print(self.request.user.id) is commented out, everything works fine. However, I've found that uncommenting it, or any type of interaction with the user field in the self.request object, causes a Recursion Error: RecursionError at /about/ maximum recursion depth exceeded Request Method: GET Request URL: http://127.0.0.1:8000/about/ Django Version: 3.2.13 Exception Type: RecursionError Exception Value: maximum recursion depth exceeded Exception Location: /opt/homebrew/lib/python3.9/site-packages/django/db/models/sql/query.py, line 192, in __init__ Python Executable: /opt/homebrew/opt/python@3.9/bin/python3.9 Python Version: 3.9.13 In the error page, that is followed by many repetitions of the below error: During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception … -
NoReverseMatch at / Reverse for 'homepage' not found. 'homepage' is not a valid view function or pattern name - django
i was tried to upload data but suddenly got error message : i was already makemigrations and migrate it. here's my code views.py : def homepage(request): form = AudioForm() audio = Audio_store.objects.all() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("homepage") context={'form':form, 'audio':audio} return render(request, "homepage.html", context=context) urls.py : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), url(r'^$', views.homepage), path('audio', views.Audio_store), ] i dont't know how it fix it. please help me -
Print Django model data as JavaScript Array
I have printed a for loop as below in my HTML Template: {% for athlete in booking.athlete.all %} {{ athlete.id }} {% endfor %} The Output in HTML is as below. <td> 1 2 3 </td> Is it possible to get the output to appear as [ "1", "2", "3" ], so we can then use this as a JS array or object? I have tried a few things from the Django Template but it does not remove the additional white space. -
how to conntect this python file to django file ? Please tell me what shoud i do next ? im creating face recognition using opencv in django
import cv2 from time import sleep def capturewebcam(image): key = cv2. waitKey(1) webcam = cv2.VideoCapture(0) sleep(2) while True: try: check, frame = webcam.read() print(check) # prints true as long as the webcam is running print(frame) # prints matrix values of each framecd cv2.imshow("Capturing", frame) key = cv2.waitKey(1) if key == ord('s'): cv2.imwrite(filename='studnet_images/saved_img.jpg', img=frame) webcam.release() print("Processing image...") img_ = cv2.imread('saved_img.jpg', cv2.IMREAD_ANYCOLOR) print("Image saved!") break elif key == ord('q'): webcam.release() cv2.destroyAllWindows() break except(KeyboardInterrupt): print("Turning off camera.") webcam.release() print("Camera off.") print("Program ended.") cv2.destroyAllWindows() break i tried so many times bt i cant understand. Please help me to reslove the problem. -
How to get field value in django Model?
I have this code class Book(models.Model): name = models.CharField(max_length=70) author = models.CharField(max_length=70) rating = models.IntegerField(default=None) volume = models.IntegerField(null=True, default=None) annotation = models.TextField(default=None) year = models.IntegerField() I want to get a value from field right in class. For example, "Harry Potter" for name. I don't find method to do it. -
selenium: Max retries exceeded with url
Full traceback: Traceback (most recent call last): File "/home/webadmin/dev.taracares.com/src/app_payroll_reports/tests.py", line 134, in test_mstnla_sums_incentives_tennessee_sum int(quince_amount_cell.text.replace(',', '')) + File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 77, in text return self._execute(Command.GET_ELEMENT_TEXT)['value'] File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 710, in _execute return self._parent.execute(command, params) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 423, in execute response = self.command_executor.execute(driver_command, params) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/remote_connection.py", line 333, in execute return self._request(command_info[0], url, body=data) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/remote_connection.py", line 355, in _request resp = self._conn.request(method, url, body=body, headers=headers) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/request.py", line 74, in request return self.request_encode_url( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/request.py", line 96, in request_encode_url return self.urlopen(method, url, **extra_kw) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/poolmanager.py", line 375, in urlopen response = conn.urlopen(method, u.request_uri, **kw) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/connectionpool.py", line 783, in urlopen return self.urlopen( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/connectionpool.py", line 783, in urlopen return self.urlopen( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/connectionpool.py", line 783, in urlopen return self.urlopen( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/connectionpool.py", line 755, in urlopen retries = retries.increment( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/util/retry.py", line 574, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=58331): Max retries exceeded with url: /session/0f8192d1-c39f-49d1-9a99-7f91dfe95481/element/a5dd2645-6c15-44dc-b000-04bf6b7ea6cb/text (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd9dcde24f0>: Failed to establish a new connection: [Errno 111] Connection refused')) This is code being run in tests for a django application. The tests used to run fine, now the last 4 tests (which use selenium) have errors, which started after I added driver.quit() after each test. … -
Accessing User objects through User.objects.filter for a profile page
I have a model called Question and Answer How can i get user information like username, email, first name, last name and the Question model into his profile. I want to display all these information in his profile page. the question model class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.CharField(max_length=50, blank=False, null=False) def __str__(self): return str(self.title) as you can see here in the Profle view i'm willing to access user email, but how can i query the database to get all these information in the profile page ? def profile(request, pk): user_profile = User.objects.filter(email=request.user) context = {'user_profile':user_profile} return render(request, 'profile.html', context) the profile template: {{user.email}} <div class="container"> <div class="row justify-content-center"> {% for question in list_of_question reversed %} <div class="col-md-4"> <div class="card my-3"> <div class="card-header"> <p class="card-title">{{question.user.username.upper}}</p> </div> <div class="card-body"> <a href="{% url 'view-Question' question.id %}" style="text-decoration: none;"> <p class="card-title">{{question.title}}</p> </a> <p>Category: {{question.category}}</p> </div> </div> </div> {%endfor%} </div> </div> -
How to automatically set ManyToMany relationship with user
How to automatically set owner field with the user which creates this event? Event model: class Event(models.Model): title = models.CharField(max_length=50, unique=True) describe = models.TextField(max_length=500) type_of_event = models.IntegerField(choices=TYPE_OF_EVENT_CHOICE, default=0) img = models.ImageField(null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) event_date = models.DateTimeField() city = models.ForeignKey(City, verbose_name='City', on_delete=models.CASCADE) address = models.CharField(max_length=60) ticket_price = models.IntegerField(default=0) email = models.EmailField(max_length=100, verbose_name='Contact email', validators=[validate_email]) Event`s view: class CreateEventView(generics.CreateAPIView): serializer_class = EventDetailSerializer permission_classes = [IsAuthenticated] Event`s serializer: class EventDetailSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ['title', 'img', 'type_of_event', 'describe', 'event_date', 'city', 'address', 'ticket_price', 'email'] -
How do I re-use <option> data in HTML forms? (Django) (DRY)
I'm generating an HTML response via Django with a large set of forms, and one of the form fields is a <select> with many (1,000+) <option>s in the queryset. Due to repeating the <option>s for each form, the HTML response is egregiously long. I've used pagination to reduce the amount of HTML rendered in each response, but this isn't optimal for the particular application. Is it possible to render the <option>s once on the HTML response and reference it in each form field without rendering it again? -
How to access the submitted value of a django form?
I am trying to make an e-commerce site that allows the user to place bids through a form. The new bid that the user posts has to be larger than the listing price on the listing and any other bids. I need help accessing the value that the user submits to check if it meets the previously stated requirements. views.py def listing(request, id): #gets listing listing = Listings.objects.get(id=id) #code for forms listing_price = listing.bid comment_obj = Comments.objects.filter(listing=listing) form = CommentForm() bid_form = BidsForm() if request.method == "POST": form = CommentForm(request.POST) bid_form = BidsForm(request.POST) new_bid = bid_form.cleaned_data.get('newBid') if form.is_valid(): comment = form.save(commit=False) comment.listing = listing comment.user = request.user comment.save() if (bid_form.is_valid()) and (new_bid >= listing_price): bid = form.save(commit=False) bid.listing = listing bid.user = request.user bid.save() else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": form, "comments": comment_obj, "bidForm": bid_form }) return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": form, "comments": comment_obj, "bidForm": bid_form }) (There are two forms, one for comments and one for bids.) html <!--bid form--> <form action = "{% url 'listing' auction_listing.id %}" method = "POST" name = "newBid"> {% csrf_token %} {{ bidForm }} <input type = "submit" value = "Place Bid"> </form> -
Convert a list of dictionaries to a dictionary of dictionaries
I have a list of dictionaries in python3, that form a pyramid-type structure of 5 levels top, and i need to convert to a dictionary of dictionary in base to one value. for example the list: [{"name":"exampleName2", "referal":"exampleName1", "data":"data"}, {"name":"exampleName3", "referal":"exampleName2", "data":"data"}, {"name":"exampleName4", "referal":"exampleName3", "data":"data"}] need to be converted to: {"name:"exampleName1", "refered":[{"name:"exampleName2", "refered":[{"name:"exampleName3", "refered":[{"name:"exampleName4", "refered":[], "data":"data}], "data":"data}], "data":"data}], "data":"data} I could do a lot of for and while loops, but i think there is a fast method. My method at the moment is: try: porOrdenar = LISTADO ordenados = [] while len(porOrdernar) > 0: n = 0 while n < len(porOrdernar): if porOrdernar[n]["referal"]=="uno": ordenados.append(porOrdernar[n]) porOrdernar.pop(n) for element in ordenados: unirReferidos(porOrdernar, n, element1) for element1 in element["referidos"]: unirReferidos(porOrdernar, n, element1) for element2 in element1["referidos"]: unirReferidos(porOrdernar, n, element2) for element3 in element2["referidos"]: unirReferidos(porOrdernar, n, element3) n +=1 except IndexError: pass def unirReferidos(porOrdernar, n, element3): if porOrdernar[n]["referal"] == element3["name"]: element3["refered"].append(porOrdernar[n]) porOrdernar.pop(n) -
CSS not applying to html
I'm trying to attach a CSS file to my HTML files, but when I run the server on localhost the CSS isn't being applied. I have gone through quite a bit of troubleshooting but every time I end up just having to put the styling I want straight into the HTML document as it won't apply if left in the CSS document and linked through via class="". style.css: .remove-default-btn { background-color: transparent; border: none; box-shadow: none; } .edit-color { color: #333 } .post-link { text-decoration: none; } .post-text { padding-top: 0.5rem; } .post-img { float: left; margin-right: 1rem; } .child-comment { margin-left: 2rem; } .notification-badge { transition: 0.3s; } .notification-badge:hover { cursor: pointer; opacity: 0.75; transition: 0.3s; } .dropdown { position: relative; display: inline-block; } .dropdown-content { position: absolute; background-color: #f1f1f1; min-width: 350px; box-shadow: 0px 8px 8px 0px rgba(0,0,0,0.2); z-index: 1; font-size: 0.9rem; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover { background-color: #ddd; } .dropdown-item-parent { position: relative; display: block; } .dropdown-item-close { position: absolute; top: 0; right: 0; font-size: 1.8rem; padding-right: 5px; transition: 0.3s; } .dropdown-item-close:hover { color: rgb(180, 25, 25); transition: 0.3s; cursor: pointer; } show_notifications.html: <div class="dropdown"> <span … -
docker container for Django hangs when updating mounting sources
As part of a course I am currently passing there is a situation when following combination is used: A docker container is created for very standard scenario: One for Django, second one for Postgresql database and then a compose file is managing all this stuff. And the sources are actually mounted using the docker-compose volumes. The entire application I created during the course is available in my github: https://github.com/arsenhakobyan/recipe-app-api The problem I faced is with running django test command each time when I update any source file. steps to reproduce the issue I have: build images with docker-compose build run the following command: docker-compose run --rm app sh -c "python manage.py test" The process should run as expected. Edit any file (e.g. app->user->tests->test_user_api.py) and save the changes run the command from step 2. the process hangs at this point in my case and I can not even force to remove the docker containers, even tried to deactivate some endpoints from the network that is connected with that containers (I think that could help when I read some of the error messages). The only way to continue work is to restart the docker exe on my machine. Let me know if … -
How to connect two databases in django for local and remote servers?
guys. I have a database, which I deployed on Heroku. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'd7mj3h2mco40v9', 'USER': 'fwla1qyxgxrrqk', 'PASSWORD': get_secret('DB_PASSWORD'), 'HOST': 'ec2-54-174-73-136.compute-1.amazonaws.com', 'PORT': '5432', } } The problem is when I add comments objects on a local machine, they automatically downloaded to the remote database. It's not convenient. I want to create, for example, a local database which will save all migrations or changes of my models, but not downloaded into a remote server. And when I need to download the data, I will do something and the changes are to appear on a remote database. What do I need to do for this? How to make the right migrations and then work with them? I'm newbie, please don't advice complicated things I can't understand :) -
is there any way in django to list all devices a user logged in?
I am trying to list all the device and their locations on which a user account is logged in . similar to login activity of instagram, is there any way to do this? sorry for my bad english 😅 -
django rest upload multiple images
I'm working on an e-commerce API with Django rest framework so I want when the user adds a new product he can upload multiple images how can I do that with rest framework? here are my models, views, serializer my models.py class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(null=True, blank=True) owner = models.ForeignKey(User, related_name='Products', on_delete=models.CASCADE,null=True) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images') images = models.FileField(upload_to='API/images',max_length=100,null=True) my serializer class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImages fields = '__all__' class Productserializer(serializers.ModelSerializer) : images= ProductImageSerializer(many=True) class Meta: model = Product fields = ('id','title','price','description','whatfor','categories','size','rooms','Location','Lat','Long','owner_id','images') extra_kwargs = {"user":{"read_only":True}} def validate(self, attrs): attrs['owner'] = self.context.get("request").user return attrs my views class ProductViewSet(ModelViewSet): queryset = Product.objects.all() serializer_class = Productserializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_class = ProductFilter search_fields = ['title', 'description'] ordering_fields = ['price', 'last_update'] def get_serializer_context(self): return {'request': self.request}