Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
/admin/password_change/ and /accounts/password_change/ use the same template unless I manually specify some urlpatterns
Problem I am using both django auth and django admin. After registering these in urls.py, visiting /accounts/password_change/ and /admin/password_change/ are using the same template. This is not what I want. Environment The following is my project layout, or at least the relevant parts: . +-- config | +-- settings.py | +-- urls.py +-- timelog | +-- templates | | +-- registration | | | +-- password_change_done.html | | | +-- password_change.html | | +-- app1 | | | +-- (templates) | | +-- app1 | | | +-- (templates) | +-- app1 | +-- app2 +-- manage.py TEMPLATES setting: from pathlib import Path ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent APPS_DIR = ROOT_DIR / "timelog" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [str(APPS_DIR / "templates")], "APP_DIRS": True, } ] urls.py: from django.conf.urls import include from django.contrib import admin from django.urls import path urlpatterns = [ path("accounts/", include("django.contrib.auth.urls")), path("admin/", admin.site.urls), ] Current workaround The only solution I found was to override /accounts/password_change/ and /accounts/password_change/done/. I found it necessary to rename the templates so that include("django.contrib.auth.urls") wouldn't screw things up. Updated urls.py from django.conf.urls import include from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path urlpatterns = [ path( "accounts/password_change/", auth_views.PasswordChangeView.as_view(template_name="registration/change_password.html"), … -
How to know the count of many to many fields of an random model?
I have an random model: class Model(models.Model): other_field1 = models.SomeField(...) m2m_field1 = models.ManyToManyField(...) other_field2 = models.SomeField(...) m2m_field2 = models.ManyToManyField(...) other_field3 = models.SomeField(...) I want to know the count of fields that correspond to the relation many to many and the count of other fields. In the example above, I have 2 fields with a many-to-many relationship and 3 other fields. -
How to allow the update of only 1 field?
So Im doing an app where the user can upload photos, each photo has a user, image, description, and other fields. When the user creates a new photo, the image is required, but when the user wants to update it, you only can change the description. I'm stuck with this, first tried with update (put) but it's clearly not the method to use, now I'm trying with partial_update but I can't get it right. This is what I have right now, it gives me the error: TypeError: Object of type Photo is not JSON serializable. Maybe it's a completely wrong way of doing it. View: class PhotoViewSet(mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): """ PhotoViewSet Handle upload (create) and delete of photos. """ queryset = Photo.objects.all() serializer_class = PhotoModelSerializer def perfom_create(self, serializer): """ Upload a new photo. """ serializer.save() def perform_destroy(self, instance): """ Delete a photo. """ return super().perform_destroy(instance) def retrieve(self, request, *args, **kwargs): """ Retrieve photo information. """ response = super(PhotoViewSet, self).retrieve(request, *args, **kwargs) data = { 'photo': response.data, } response.data = data return response def partial_update(self, request, pk=None): serializer = UpdateDescriptionSerializer(data=request.data, partial=True) serializer.is_valid(raise_exception=True) data = serializer.save() return Response(data=data, status=status.HTTP_202_ACCEPTED) serializer: class UpdateDescriptionSerializer(serializers.ModelSerializer): """ Update description serializer. """ description = serializers.CharField(max_length=255) … -
Get queryset and it's aggregated value at one db query
In Django rest framework view I am making a complex Product annotated queryset which goes to serialization, but at the same time, I need to get its aggregation data to add it to the Response data. Example (one query): qs = self.filter_queryset(Product.objects.filter(**query_filters) .annotate(current_price=F('some_value') * some_vart))) Then I need aggregated data(second query): min_max = qs.aggregate(Max('current_price'), Min('current_price')) This produces 2 DB queries total. Is there any way to make it hitting DB once? DB is Postgres. Thx -
Django migrations weren't unapplied
I've developed a custom package to sync some models with s3 bucket. When I installed it on my django app, and ran the CI, the migrations weren't unapplied. The unapplying migrations are behaving unexpectedly: It tries to unapply twice the same migration (recommendations.0011_auto_20210725_1253): Operations to perform: Unapply all migrations: lakehouse_sync Running migrations: Rendering model states... DONE Unapplying lakehouse_sync.0001_initial... OK INFO:botocore.credentials:Found credentials in shared credentials file: ~/.aws/credentials Operations to perform: Unapply all migrations: profiles Running migrations: Rendering model states... DONE [...] Unapplying recommendations.0011_auto_20210725_1253... OK [...] Operations to perform: Unapply all migrations: recommendations Running migrations: Rendering model states... DONE Unapplying recommendations.0011_auto_20210725_1253 And it happens because Django doesn't detect that they were unapplied. lakehouse_sync [X] 0001_initial profiles [X] 0001_initial [X] 0002_auto_20210723_0857 recommendations [...] [X] 0011_auto_20210725_1253 However, there aren't those tables on my db I have no idea how to proceed with that, could someone give me a clue at least to solve this issue? -
Which stack, technologies and tools for building online store?
I want to build an online store for subscription boxes with recurrent payments. I study computer science and have experience in most of the popular programming languages (have been using python for the last semesters). Which stack, technologies and tools do you recommend me to use? And any other tips for building an online store. -
Django run javascript before render_to_string
I am building a application that dynamically fill in forms and converts it to pdf. To build the pdf I pass in html code (pdfkit.from_string()) and to build the html code I am using Django templates. I need to run some Javascript code to mark some input checkboxes as checked, however render_to_string will just generate the html without running the javascript to mark the items as checked. my_template.html {{checked_items|json_script:'items'}} <script src="{% static 'form_render.js' %}"></script> form_render.js const items = JSON.parse(document.getElementById("items").textContent); let form_checkboxes = document.querySelectorAll('input[name="my_checkboxes"]'); for (let i of form_checkboxes) { items.includes(i.value) ? (i.checked = true) : ""; } views.py rendered = render_to_string( "my_app/my_template.html", {"checked_items": checked_items_json}, ) -
Make Swagger UI to use HTML Form to submit request body, just like DRF's browsable API
In django-rest-framework's browsable API, there is an HTML form to submit in the request body. Swagger on the other hand lets you edit a JSON formatted text as the request body. How to make Swagger UI show HTML form, just like DRF's browsable API in swagger? -
Pyhton django, when creating an registering form how to get this .get method working?
I started to watch Corey Schafer's django website tutorial and everything was going great until now. unlike in the video after registering site doesn't sends me to home page. It does nothing. All I suspect is the get method because it is not the color it supposed to be in VSC. Any ideas why :( and also .method functions seems to be not working it is white in VSC from django.contrib import messages from django.contrib.auth.forms import UserCreationForm from django.shortcuts import redirect, render def register(request): if request.method =='POST': form = UserCreationForm(request.POST) if form.is_valid(): username=form.cleaned_data.get('username') messages.success(request,f'Account Created for {username}') return redirect("blog-home") else: form=UserCreationForm() return render(request,'users/register.html',{'form':form}) -
Django: How to delete models in real time
I am working on a subscriber confirmation system with Django, and I do not want random/spam subscribers. So I came up with a confirmation system. Once the subscriber clicks the subscribe button, a Subscriber model is created. However, it is not confirmed. I send a confirmation email and only if the subscriber clicks on the link in the email will the model be confirmed. The problem with this system is that an unconfirmed subscriber stays and is not deleted. How do I write a function that deletes the unconfirmed subscribers if they did not confirm in, say, 2 days? models.py class Subscriber(models.Model): email = models.EmailField(unique=True) confirmed = models.BooleanField(default=False) creation_date = models.DateTimeField('date published', blank=True, null=True) #my function for deleting subscribers def confirm_date(self): today = date.today().toordinal() if today - self.ordinal_creation >= 2 and self.confirmed == False: self.delete() -
how do I create an online compiler? like TIO?
So, I'm working on a hobby project, and so basically what I want is something like 'TIO' (try it online) Where the user would enter the 'code' hit 'Run', and the server would return the appropriate output firstly I was thinking of using a third party library Python-tio-github and simply sending a request to the 'Tio' website, but that doesn't seem right, I mean is that allowed?, is there any other way? how am I supposed to go about it? My Setup: I'm using Django, 'Rest Api' with Angular 10, and I'm planning on running this on Digital Ocean I could run the TIO on my website server (as it's open-source) but I doubt the server would be able to handle it? running Django, node(angular), and MySQL along with TIO? the main goal of this project is for me to learn, so, even if I could have only a single language compile (Python) I'd be happy, I just don't have ANY clue on how and where I'd start looking. thanks in advance! -
paypal sandbox not working after adding the client id
hello everyone im sorry if this is a silly question ,it's my first time trying to integrate paypal payment button to my django website i was following a tutorial and everything works fine when i used the html script from paypal developer website : https://developer.paypal.com/demo/checkout/#/pattern/client i tested the payments and it went through successfully. this is the working script <!-- Set up a container element for the button --> <div id="paypal-button-container"></div> <!-- Include the PayPal JavaScript SDK --> <script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script> <script> // Render the PayPal button into #paypal-button-container paypal.Buttons({ // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '88.44' } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(orderData) { // Successful capture! For demo purposes: console.log('Capture result', orderData, JSON.stringify(orderData, null, 2)); var transaction = orderData.purchase_units[0].payments.captures[0]; alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details'); // Replace the above to show a success message within this page, e.g. // const element = document.getElementById('paypal-button-container'); // element.innerHTML = ''; // element.innerHTML = '<h3>Thank you for your payment!</h3>'; // Or go to another URL: actions.redirect('thank_you.html'); }); } }).render('#paypal-button-container'); </script> on the final step i should add … -
couldn't makemigrations in django
i had this erreur . Traceback (most recent call last): File "C:\Users\abdou\Documents\Djangoprojects\DjangoAPI\manage.py", line 22, in main() File "C:\Users\abdou\Documents\Djangoprojects\DjangoAPI\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init_.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init_.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\makemigrations.py", line 103, in handle loader.check_consistent_history(connection) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 294, in check_consistent_history applied = recorder.applied_migrations() File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table tables = self.connection.introspection.table_names(cursor) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\introspection.py", line 52, in table_names return get_names(cursor) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\introspection.py", line 47, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\database.py", line 880, in list_collection_names for result in self.list_collections(session=session, **kwargs)] File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\database.py", line 842, in list_collections return self.__client._retryable_read( File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\mongo_client.py", line 1514, in _retryable_read server = self._select_server( File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\mongo_client.py", line 1346, in _select_server server = topology.select_server(server_selector) File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\topology.py", line 244, in select_server return random.choice(self.select_servers(selector, File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\topology.py", line 202, in select_servers server_descriptions = self._select_servers_loop( File "C:\Users\abdou\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\topology.py", line 218, in _select_servers_loop raise ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: djangoapi-shard-00-02.wqh9l.mongodb.net:27017: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get … -
Update Django ImageField through .update() ORM
Similar questions have been asked here: Update ImageField without forms in django, and Django ImageField is not updating when update() method is used But the answer has always been the same ("use .save() instead") - this solution does work, but because of signals on the model which I can't control, I would like to know if there are any work-arounds that can be used instead. # serializers.py from drf_extra_fields.fields import Base64ImageField from rest_framework import serializers class ProfileSerializer(serializers.Serializer): email = serializers.CharField(required=False, allow_null=True) image = Base64ImageField(required=False, allow_null=True, max_length=None, use_url=True) # views.py def get_as_base64(url: AnyStr): if url is None: return None, None full_name = url.split("/")[-1] my_base = base64.b64encode(requests.get(url).content) return my_base, full_name def do_profile_update(profile: Dict): b64_image, file_name = get_as_base64(profile.get("url")) if b64_image and file_name: *_, file_ext = file_name.split(".") b64_image = f"data:image/{file_ext};base64,{b64_image.decode('utf-8')}" build_dict = { "email": profile.get("email"), "image": b64_image, } serializer = ProfileSerializer(data=build_dict) serializer.is_valid() # returns True # serializer.validated_data = {'email': 'test@example.org', 'image': <SimpleUploadedFile: 11735acf-6d96-4c62-9e6a-8ebb7f7ea509.jpg (image/jpeg)>} Profile.objects.filter(pk=pk).update(**serializer.validated_data) # This saves the *name* of the image to the database, but no image file I understand that a ImageField is basically a CharField, and I can see the name of the image in the database, but the image isn't written to the server. My question boils down to: … -
Is there a way to install pymssql with the python2.7?
Collecting pymssql Using cached pymssql-2.2.2.tar.gz (170 kB) Installing build dependencies ... error ERROR: Command errored out with exit status 1: command: 'C:\Python27\python.exe' 'C:\Python27\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'c:\users\connor~1\appdata\local\temp\pip-build-env-jbbmyu\overlay' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=54.0' 'setuptools_scm[toml]>=5.0' 'wheel>=0.36.2' 'Cython>=0.29.22' cwd: None Complete output (3 lines): DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality. ERROR: Could not find a version that satisfies the requirement setuptools>=54.0 (from versions: 0.6b1, 0.6b2, 0.6b3, 0.6b4, 0.6rc1, 0.6rc2, 0.6rc3, 0.6rc4, 0.6rc5, 0.6rc6, 0.6rc7, 0.6rc8, 0.6rc9, 0.6rc10, 0.6rc11, 0.7.2, 0.7.3, 0.7.4, 0.7.5, 0.7.6, 0.7.7, 0.7.8, 0.8, 0.9, 0.9.1, 0.9.2, 0.9.3, 0.9.4, 0.9.5, 0.9.6, 0.9.7, 0.9.8, 1.0, 1.1, 1.1.1, 1.1.2, 1.1.3, 1.1.4, 1.1.5, 1.1.6, 1.1.7, 1.2, 1.3, 1.3.1, 1.3.2, 1.4, 1.4.1, 1.4.2, 2.0, 2.0.1, 2.0.2, 2.1, 2.1.1, 2.1.2, 2.2, 3.0, 3.0.1, 3.0.2, 3.1, 3.2, 3.3, 3.4, 3.4.1, 3.4.2, 3.4.3, 3.4.4, 3.5, 3.5.1, 3.5.2, 3.6, 3.7, 3.7.1, 3.8, 3.8.1, 4.0, 4.0.1, 5.0, 5.0.1, 5.0.2, 5.1, 5.2, 5.3, 5.4, 5.4.1, 5.4.2, … -
I am using XPATH on selenium in python and I understand the issue selenium.common.exceptions.JavascriptException: Message: Cyclic object value
First, I am a newbie in Selenium in Python. I am working on a website in Django Framework. I want to do unit tests in order to make the website project with an higher quality. The Error selenium.common.exceptions.JavascriptException: Message: Cyclic object value Introduction I do my test in tests_functionals.py which is a file containing selenium. I use XPATH in order to retrieve elements on the DOM. In the index.html of the website, I have those links : <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="/home">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="/about">About</a> </li> <li class="nav-item"> <a class="nav-link" href="/corpora">Corpora</a> </li> <li class="nav-item"> <a class="nav-link" href="/approaches">Approaches</a> </li> <li class="nav-item"> <a class="nav-link" href="/ML">Machine Learning</a> </li> </ul> I use BaseX software to test my XPATH paths. I have sorry but I cannot show you pictures because I am new in stackoverflow so I don't have enough reputation to show pictures. Here if ou want to learn more about BaseX I use this path : //header/nav/div/ul/li/a/@href And on BaseX I have this result: href="/home" href="/about" href="/corpora" href="/approaches" href="/ML" My problem in Django I will show you a piece of this code in order to make you understand what I am talking. from selenium import webdriver from … -
How to have a backend_model be associated to a Django model
I have a Ticker Model - class Ticker(models.Model): symbol = models.CharField(max_length=50, primary_key=True) company_name = models.CharField(max_length=50) def __str__(self) -> str: return f'{self.symbol}-{self.company_name}' And class Model(models.Model): ticker = models.ForeignKey(Ticker, on_delete=models.CASCADE) test_loss = models.FloatField(null=True) def __str__(self) -> str: return f'{self.ticker.symbol}' I want to add this function to Model - def predict(self, pred_date): return self.backend_model.predict(pred_date) Where - self.backend_model = LstmModel(symbol) How do I add this backend_model to Model? These are the solutions I have thought of - Have a custom Model Manager. Override save() method of Model. Add a classmethod to Model Which one should I use, or if someone can suggest a better way? -
Django dynamic formset only saving last entry
I have created a page where users can enter details to forms relating to a parent model (Patient) and two child models (CurrentMed and PastMed) linked to that parent. Both the child forms use dynamic formsets where the user can add or delete rows to the form. My problem is only the last row of the currentmed and pastmed formsets is saving to my database when the user submits the form? models.py class Patient(TimeStampedModel): # get a unique id for each patient - could perhaps use this as slug if needed patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) name = models.CharField("Patient Name", max_length=255) creator = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) class Med(TimeStampedModel): med_name = models.CharField(“med name“, max_length=20) dose = models.IntegerField("Dose (mg)", default=0) timepoint = models.CharField( "timepoint", max_length=20, choices=[('current','current'), ('past', 'past')], default='unspecified') patient = models.ForeignKey(Patient, on_delete=models.CASCADE) class Meta: abstract = True class CurrentMed(Med): timepoint = models.CharField( "", max_length=20, choices=[('current','current'), ('past', 'past')], default='current') class PastMed(Med): timepoint = models.CharField( "", max_length=20, choices=[('current','current'), ('past', 'past')], default='past') forms.py from .models import CurrentMed, PastMed, Patient CurrentmedFormSet = inlineformset_factory( Patient, CurrentMed, fields=("med_name", "dose",), extra=2) PastmedFormSet = inlineformset_factory( Patient, PastMed, fields=("med_name", "dose",), extra=2) class PatientForm(ModelForm): class Meta: model = Patient fields = ['name', 'sex', 'age', 'diagnosis'] views.py class PatientAddView(LoginRequiredMixin,TemplateView): model … -
how to show date in url django
im trying to return objects based on date (yyyy-mm-dd) but it returns this : Reverse for 'daily_detail' with arguments '(datetime.datetime(2021, 8, 19, 0, 0),)' not found. 1 pattern(s) tried: ['my/url/for/(?P\d{4}-\d{2}-\d{2})$'] this is my views.py #my lists def daily_list(request): lists = MyModel.objects.annotate(day=TruncDay('date')).values('day').order_by('-day') #this is my day detail def daily_report(request,day): daily_report = MyModel.objects.annotate(day=TruncDay('date')).filter(day=day).order_by('-pk') context = { 'daily_report':daily_report } and this is my urls.py path('list/daily',daily_list,name='daily_list'), path('list/daily/<str:day>',daily_report,name='daily_report'), but it returns the above error and this is my template {% for i in lists %} <!--other informations --> <td class="p-2 text-xs border border-purple-900 md:text-base textpurple"> <a href="{% url 'myAppUrl:daily_report' i.day %}"><button><i class="fas fa-eye"></i></button></a> </tr> {% endfor %} thank you for your suggestions ... -
How to return and display multiple tables as JsonResponse in Django?
I'm trying to display the result of two queries in different tables at my Django project. I have the following view: cursor = connections['trades_db'].cursor() sql = """Select investor from a; """ sql_II = """Select price from b; """ d = db.fetchDataDict(cursor, sql) e = db.fetchDataDict(cursor, sql_II) return JsonResponse({'d':d, 'e':e}, safe=True) I want to display the result of both queries in different HTML tables, How is possible to access to each element of the JsonResponse? so far, I was able to access to just one element by returning it individually: return JsonResponse(d, safe=True). However, I don't know to access each element when returning both queries. $.ajaxSetup({ headers: { "X-CSRFToken": getCookie("csrftoken") } }); var table = $('#maintable').DataTable( { "ajax": {"type":"GET", "url" :"/data/trades/request/", "data":function( d ) { d.placeholder = "asdf"; } }, -
Django modal popup on a list link
I would like to develop a popup on a list link (please see the screenshot) click. popup will be a list also. So far this is my code below Model class: class PSCInscpection(models.Model): vessel = models.ForeignKey(Vessel, on_delete=models.CASCADE, null=True) inspection_id = models.CharField(max_length=100, null=False, unique=True) followup_inspection = models.BooleanField(null=False, default=False) date = models.DateTimeField(null=True, blank=True) port = models.CharField(max_length=50, null=True, blank=True) country = models.CharField(max_length=50, null=True, blank=True) number_of_defects = models.PositiveIntegerField(null=True, blank=True) days_detained = models.PositiveIntegerField(null=True, blank=True) class PSCInscpectionDefects(models.Model): pscinscpection = models.ForeignKey(PSCInscpection, on_delete=models.CASCADE, null=True) inspection_id = models.CharField(max_length=100, null=False, blank=False) defect_code = models.CharField(max_length=50, null=True, blank=True) defect_text = models.CharField(max_length=255, null=True, blank=True) class_is_responsible = models.CharField(max_length=50, null=True, blank=True) defective_item_code = models.CharField(max_length=50, null=True, blank=True) My list binding from this "PSCInscpection" object and popup will bind from "PSCInscpectionDefects" object. Any help regarding please ? Thanks ! {% for inspection in inspections %} <tr> <td>{{ inspection.date }}</td> <td>{{ inspection.country }}</td> <td>{{ inspection.port }}</td> <td> {% if inspection.defects %} <a href="#">{{ inspection.defects }}</a> {% else %} {{ 0 }} {% endif %} </td> <td>{{ inspection.detained|default:0 }} Days</td> </tr> {% endfor %} -
Django CustomUser deploying and getting error: relation "accounts_customuser" does not exist
I am deploying my django to VSP using Dokku. I have the project working on my local computer but when I deploy to dokku, I'm getting errors when it tries to do the migrations. The dokku is deployed with git push dokku main:master and migrations are in my .gitignore, so migrations on my local computer are not being pushed. I am using a CustomUser model which extends AbstractUser. The problem looks to be django.db.utils.ProgrammingError: relation "accounts_customuser" does not exist. full logs/trace PS C:\> git push dokku main:master Enter passphrase for key '/c/Users/name/.ssh/id_rsa': Enumerating objects: 331, done. Counting objects: 100% (331/331), done. Delta compression using up to 16 threads Compressing objects: 100% (326/326), done. Writing objects: 100% (331/331), 1.18 MiB | 2.24 MiB/s, done. Total 331 (delta 71), reused 0 (delta 0), pack-reused 0 remote: Resolving deltas: 100% (71/71), done. remote: -----> Cleaning up... remote: -----> Building app from herokuish remote: -----> Adding BUILD_ENV to build environment... remote: -----> Python app detected remote: -----> Using Python version specified in Pipfile.lock remote: cp: cannot stat '/tmp/build/requirements.txt': No such file or directory remote: -----> Installing python-3.8.11 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing dependencies with Pipenv 2020.11.15 … -
django get path to previous parent directory on template tag
i want to extends from an base.html that is before(previous?) the parent directory. the path estructure is this: templates: base base.html <--- file i want to extends. pages general home.html <--- file from where i got the error the problem is TemplateDoesNotExist at / pages/general/base/base.html and here is the html code from home.thml in template/pages/general/base.html for call .base.html {% extends "../base/base.html" %} i dont know how i can go to the previous folder from parent directory, and i dont even know how to find documentation referenced to that, im not native english speaker so its hard to find and answer. -
Django S3 : Saving images doesn't work when calling serializer
I need to create an API to upload images on a website. I've already created in my models the save method to upload and resize images. It's working correctly by the django administration page. Unfortunately, when I use my serializer, the image does not save. Here is my model : models.py class Shop(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(ShopCategory, on_delete=models.SET_NULL, null=True, blank=True) description = models.TextField(blank=True, null=True) path = models.CharField(max_length=255, unique=True, null=True, blank=True) mustBeLogged = models.BooleanField(default=False) deliveries = models.FloatField(validators=[MinValueValidator(0),], default=7) message = models.TextField(null=True, blank=True) banner = models.ImageField(null=True, blank=True) def save(self, *args, **kwargs): try: """If we want to update""" this = Shop.objects.get(id=self.id) if self.banner: image_resize(self.banner, 300, 300) if this.banner != self.banner: this.banner.delete(save=False) else: this.banner.delete(save=False) except: """If we want to create a shop""" if self.banner: image_resize(self.banner, 300, 300) super().save(*args, **kwargs) def delete(self): self.banner.delete(save=False) super().delete() def __str__(self): return self.name banner is the imagefield that I have to save. Here is my serializer : serializers.py class ShopSerializer(serializers.ModelSerializer): links = serializers.SerializerMethodField() isOwner = serializers.SerializerMethodField() banner = serializers.SerializerMethodField() class Meta: model = Shop fields = '__all__' def get_links(self, obj): links = Link.objects.filter(shop=obj) data = LinkSerializer(links, many=True).data return data def get_banner(self, obj): """Get a link for the banner""" if obj.banner: url = f"https://myurl/v1/images/{obj.banner.name}" return url def get_isOwner(self, obj): … -
How to add product to cart on a page with many products in E-commerce Vue.js / Django Rest Framework?
I am building an e-commerce website with Vue.js and Django Rest Framework. I have a page with all the latest products, that works well and fetches all the data. I can visit the details of each product and add them to the cart (on each product's page). The problem is that I don't know and can't get to add those products from the general products page where there are multiple products and get the number of products of each one of them. I created a dynamic Id for number input, but when I try to use it it says "Cannot read property 'value' of null" I understand that the number of products should be related to each one of the products, but I can't seem to understand how to do that. To sum things up: How can I add products to the cart on a page with multiple products fetched via v-for? Thank you! This is my Vue.js Products page code: <template> <div id="productapp"> <!-- Intro Section --> <div class="row" id="home__screen"> <div class="col-lg-12 text-center align-self-center decorator__spacing"> <h1 class="mt-5 mb-4 text-white">Conoce nuestros productos</h1> <button type="button" class="btn btn-light pl-3 pr-3 fw-bold main__text__color">VER MÁS</button> </div> </div> <!-- About Section --> <div class="w-100 bg-white …