Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Como criar um campo personalizado de modelo no django que funcione como uma lista que armazena objetos de uma outra tabela? [closed]
Estou fazendo um crud onde eu tenho uma tabela de empréstimo de livros, e preciso de um campo da model do django que funcione como um array ou lista de objetos para armazenar 1 ou mais livros que serão emprestados. Obs: Livro também é um tabela armazenada no banco de dados. E também se for possível fazer isso utilizando os próprios relacionamentos foreignkey ou manytomanyfield fornecidos pelo Django, se puderem me dar alguns exemplos de como fazer isso. -
Difference between declaring and excluding models when using dumpdata?
I'm having serialization dependency errors when trying to use dumpdata (or tests!) and am trying to diagnose the source of the problem by dumping various combinations of models to see which ones throw errors. When I explicitly declare every model except for two, it works: python manage.py dumpdata app1.ActionItem app1.ActivityLog app1.Aim app1.Bank app1.BenchmarkCategory app1.BenchmarkValue app1.Benchmark app1.Citation app1.City app1.Client app1.ComplaintStage app1.ComplaintSubscription app1.Complaint app1.Contact app1.Country app1.DocumentCategory app1.Document app1.ExplanationCategory app1.Explanation app1.FAQ app1.GoalUpdate app1.Goal app1.Group app1.IAM app1.IFISupport app1.Investment app1.Issue app1.KeyDateCategory app1.KeyDate app1.KeyTerm app1.Language app1.NCP app1.NoteCategory app1.Note app1.OrgType app1.Organization app1.Outcome app1.Region app1.ResearchRequest app1.Sector app1.Source app1.SubGoal app1.SupportItem app1.Tag app1.Team app1.TimePeriod app1.UserProfile app1.Workplan app2 app3 app4 --natural-primary --natural-foreign --output='data_dump.json' -v=3 --indent=4 --traceback But when I try dumpdata by excluding those two models, it throws the same dependency error: python manage.py dumpdata -e=app1.project -e=app1.case --natural-primary --natural-foreign --output='complaint_dump.json' -v=3 --indent=4 --traceback RuntimeError: Can't resolve dependencies for app1.ActionItem, app1.ActivityLog, app2.AnnualEvaluation, app1.Case, app1.Citation, app2.Commitment, app1.Complaint, app1.ComplaintStage, app1.ComplaintSubscription, app1.Contact, app1.Document, app2.Feedback, app1.Goal, app2.Goal, app1.GoalUpdate, app1.Investment, app1.KeyDate, app1.Note, app3.OCR, app1.Project, app2.QuarterlyUpdate, app1.ResearchRequest, app1.Source, app1.SubGoal, app4.Subscription, app1.SupportItem, app3.Survey, app2.Tactic, app1.UserProfile, app1.Workplan in serialized app list. Note that even the excluded models are showing up in the error. Am I running the exclude incorrectly somehow? -
Django 2.2 - checking user permission (perms.blog.change_blogpost) not working
So I've been stuck on this for days, not kidding. I've looked at over 20 different websites, all about Django user permissions. I cannot get the code to work not matter what I do. I've tried EVERYTHING! See below. Here is the code: models.py from django.db import models from django.conf import settings from django.utils import timezone from django.db.models import Q User = settings.AUTH_USER_MODEL class BlogPostQuerySet(models.QuerySet): def published(self): now = timezone.now() return self.filter(publish_date__lte=now) def search(self, query): lookup = ( Q(title__icontains=query) | Q(content__icontains=query) | Q(slug__icontains=query) | Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) | Q(user__username__icontains=query) | Q(user__email__icontains=query) | Q(image__icontains=query) ) return self.filter(lookup) class BlogPostManager(models.Manager): def get_queryset(self): return BlogPostQuerySet(self.model, using=self._db) def published(self): return self.get_queryset().published() def search(self, query=None): if query is None: return self.get_queryset().none() return self.get_queryset().published().search(query) class BlogPost(models.Model): # blogpost_set -> queryset user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) image = models.ImageField(upload_to='image/', blank=True, null=True) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) # Example: "hello world" -> hello-world content = models.TextField(null=True, blank=True) publish_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = BlogPostManager() class Meta: ordering = ['-publish_date','-updated','-timestamp'] def get_absolute_url(self): return f"/blog/{self.slug}" def get_edit_url(self): return f"{self.get_absolute_url()}/edit" def get_delete_url(self): return f"{self.get_absolute_url()}/delete" views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404 from .models import BlogPost from .forms import … -
Accessing an api running in a docker host from a different docker host
I have two docker projects each with their own docker-compose.yml files. One project holds a django api with docker host for that, while the other project is for open edx which running on another docker host. If I try to access my django api from one of these docker containers of the second docker host using docker exec -it edx.devstack.studio curl http://localhost:8000/number/, I get an error curl: (7) Failed to connect to localhost port 8000: Connection refused. I'm by no means a docker expert so there's something I'm probably doing wrong. I tried adding all the docker services in both projects to the same network but it still failed, probably I'm doing it wrong. Any help will be much appreciated. Below are the two docker compose files. Django project docker compose file version: "3" services: db: image: mysql:5.7 container_name: db env_file: - .env ports: - '3307:3307' expose: - '3307' volumes: - my-db:/var/lib/mysql django: build: context: . container_name: web env_file: - .env command: python src/manage.py runserver 0.0.0.0:8000 depends_on: - db ports: - "8000:8000" volumes: - .:/app networks: - okay networks: okay: external: true volumes: my-db: Open edx docker compose file # This file contains all of the services for an edX … -
annotate: whether a given value exists in m2m field
I have a query that retrieve an object like this: { "id": 1, "tags": [1, 2, 3] } I want to check whether a given tag (say, 1) exists in the tags field of the object, and annotate the result of the check as a field of the object: { "id": 1, "tagged": true } This is what I came up with annotate( tagged=Exists( Articles.tag_set.through.objects.filter( article_id=OuterRef("pk"), tag_id=tag.id ) ) ) Since the relation tags is already loaded by the primary query, having a secondary query seems redundant to me. Is there an easier way to structure this query? Something close to the filter syntax tags__contains=tag. -
Getting sqlite3.OperationalError: no such column: REFERRED.id when i'm trying to migrate
I just added new imageField to my Item model. Then run the command makemigrations, after migrate command i started to get "sqlite3.OperationalError: no such column: REFERRED.id". Then i deleted changes and try to migrate and still have the same error. i tried all the same discussions before, but nothing changes. still have the same error. So i can not add any field becouse of this error class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length = 2) label = models.CharField(choices=LABEL_CHOICES, max_length = 1) slug = models.SlugField() description = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('core:''product', kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse('core:''add-to-cart', kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse('core:''remove-from-cart', kwargs={ 'slug': self.slug }) This is traceback: (env) PS C:\Users\User\desktop\dj-projects\django_project_boilerplate> python manage.py migrate Operations to perform: Apply all migrations: account, admin, auth, contenttypes, core, sessions, sites, socialaccount Running migrations: Applying core.0013_auto_20191119_2152...Traceback (most recent call last): File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "C:\Users\User\desktop\dj-projects\django_project_boilerplate\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 381, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such column: REFERRED.id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) … -
Read a Django UploadedFile into a pandas DataFrame
I am attempting to read a .csv file uploaded to Django into a DataFrame. I am following the instructions and the Django REST Framework page for uploading files. When I PUT a .csv file to a defined endpoint I end up with a Django UploadedFile object, in particular, a TemporaryUploadedFile. I am trying to read this object into a pandas Dataframe using read_csv, however, there is additional formatting around the temporary uploaded file. I am wondering how to read the original .csv file that was uploaded. According to the DRF docs, I have assigned: file_obj = request.data['file'] Inside of a Python debugging console, I see: ipdb> file_obj <TemporaryUploadedFile: foobar.csv (multipart/form-data; boundary=--------------------------044608164241682586561733)> Things I've tried so far. With the original file path, I can read it into pandas like this. dataframe = pd.read_csv(open("foobar.csv", "rb")) However, the original file has additional metadata added by Django during the upload process. ipdb> pd.read_csv(open(file_obj.temporary_file_path(), "rb")) *** pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 5, saw 32 If I try to use the UploadedFile.read() method, I run into the following issue. ipdb> dataframe = pd.read_csv(file_obj.read()) *** OSError: Expected file path name or file-like object, got <class 'bytes'> type Thanks! -
DJango - Custom parameters to formset forms
forms.py class InsereIdioma(forms.ModelForm): class Meta: model = Idioma fields = '__all__' exclude = ['usuario'] labels = { 'idioma': 'Idioma', 'fluencia': 'Fluencia', } widgets={ 'idioma': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Idioma'}), 'fluencia': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Fluencia'}) } def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(InsereIdioma, self).__init__(*args, **kwargs) def save(self, commit=True): obj = super(InsereIdioma, self).save(commit=False) obj.usuario = self.user if commit: obj.save() return obj InsereIdiomaFormset = modelformset_factory( Idioma, fields=('idioma', 'fluencia', ), extra=1, widgets={ 'idioma': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Idioma'}), 'fluencia': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Fluencia'}), } ) views.py def cadastro_curriculo(request): if request.method == 'GET': formset = InsereIdiomaFormset(queryset=Idioma.objects.none()) elif request.method == 'POST': formset = InsereIdiomaFormset(request.POST, user=request.user) if formset.is_valid(): for form in formset: if form.cleaned_data.get('idioma'): form.save() return redirect('vagas') return render(request, "personal/curriculo.html", { 'formset': formset, }) How do I pass my custom parameters in my form to the formset so I can use it in my view? I tried to read the documentations but didn't understand as well. https://docs.djangoproject.com/en/2.2/topics/forms/formsets/#passing-custom-parameters-to-formset-forms -
Django PostgreSQL existing database does not exist
I have a table tablename with schema sub in PostgreSQL that definitely exists--it has been created, it has had data added to it, and when I run SELECT * FROM sub.tablename in pgAdmin 4, it returns results without issue. When I try to then access that same table in my Django application, it produces error psycopg2.OperationalError: FATAL: database "main.sub.tablename" does not exist. I attempted making the table name sub.tablename and tablename but it still claims the table does not exist. I am the owner of sub and it is my credentials used to access the table. I have confirmed that the host name and the port are what they should be. I'm at a loss as to how to fix this since, as far as I can tell, this error only shows up when people haven't actually created the table yet or misspell something. Below is my relevant code blurb in settings.py where the table/database info appears. settings.py DATABASES = { 'default': { 'NAME': 'tablename', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '1234', } } Traceback Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File … -
I want to know which <a> Tab was clicked and get the value of that in my View and write a logic with that
Search.py {% block search %} <form action="#" method="post"> <div class="container"> <br> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" name="bankname" type="submit" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Name </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for key , value in data_dict.items %} <a class="dropdown-item" value={{key}} name={{key}} href="{% url 'details' %}">{{ key}} </a> {% endfor %} </div> </div> </form> {%endblock%} the number of items in data_dict is not always same , so some times it has 2 or 3 or even 10 different names which leads to 10 items in the drop down. I need to show details of the name clicked in the drop down in details .html Views.py def bankdetails(request, **kwargs): value1 = None data_dict = request.session.get("data_dict") for key, value in data_dict.items(): key1 = request.GET.get("key") if key1 == key: value1 = value context = {"data_dict" : data_dict , "value1":value1} return render(request , "details.html", context ) i want the value of the tab clicked in the drop-down in my view so i can display the details accordingly from my data_dict -
Django Relations with Models
I try to figure a clever way out for my models. I have two models where i want the Legend to have 4 different skills(Skill Model), but I cant seem to get the fitting model relation for it class Skill(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) title = models.CharField(max_length=100) description = models.CharField(max_length=300) image = models.ImageField(upload_to='skills/', blank=True, null=True) class Legend(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) title = models.CharField(max_length=100) description = models.CharField(max_length=1000) image = models.ImageField(upload_to='legends/%Y/', blank=True, null=True) skill_1 = models.(Skill, on_delete=models.SET_NULL, null=True) skill_2 = models.OneToOneField(Skill, on_delete=models.SET_NULL, null=True) skill_3 = models.OneToOneField(Skill, on_delete=models.SET_NULL, null=True) skill_4 = models.OneToOneField(Skill, on_delete=models.SET_NULL, null=True) The problem is I cant rly make a OneToOneField because it want´s a related_name for each, which would make No sense here, since they are all skills and I dont want to call for the owner (Legend) of the skill in 4 different ways I also tried to make a legend field in the Skill model with a foreignkey on the Legend, but that didnt turned out how i wanted it to be. thanks for the help ^.^ -
Validate across nested serializers with django rest framework
If you were to have a nested serializer, but required a certain parameter in the parent depending on a value in the child, how could you enforce the logical requirement when necessary? For example: class ChildSerializer(serializers.ModelSerializer): foobar_attribute = serializers.ChoiceField( required=True, choices=foobar_choices, ) class ParentSerializer(serializers.ModelSerializer): child = ChildSerializer(required=True) optional_attribute = serializers.CharField( required=False, ) optional_attribute should be required only when foobar_attribute is a certain choice, but optional for all else. Throwing a validate function on ParentSerializer or ChildSerializer only exposes attributes for that serializer, and none else. How can I perform validation across nested serializers without creating rows ( as would occur if validation was performed in perform_create )? -
Deploy Machine learning Models with Django
I'm following Piotr Płoński's guide on Deploying ML models with Django Currently where I am in the Guide: https://www.deploymachinelearning.com/#algorithms-registry (Just above this section) I got this point but my server doesn't want to run when I type in python manage.py test apps.ml.tests as the guide says in the guide. The error of that I am getting OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap> Have any of you had this error before? and what's the fix? Some searches I did say its a path or URL error but I don't see any URLs or paths in the code (Might be mistaken) I saw that Piotr Płoński is on Stackoverflow @pplonski wonder if I can hear from the man himself :D If anyone could assist or point me in the right direction that would be appreciated. Kind Regards, -
Where is this mystery cache in Apache?
I have a django app running in a virtualenv on Windows 10 WSL1 (Ubuntu). The python version is 3.6.8. When using the django development web server, python manage.py runserver, everything is fine. I access that with http://localhost:8000/<my app name>/ But when using apache2, version 2.4.29, months-old javascript code shows up in the browser debugger in a VMxxx file, though I haven't yet found an eval() that's generating that. Also, old server-side code shows up: an old javascript error that resulted from the django python code sending the wrong content type - a bug that was fixed a couple of weeks ago. I'm accessing apache2 with http://localhost/<my app name>/ I disabled mod_cache: a2dismod cache Module cache already disabled. Also ran htcacheclean -r -l1k and manually looked at the page cache directory, which was empty. I clear the Chrome cache on every page load, but also get the same errors when using a different browser (Firefox) that wasn't even installed when this old code that's showing up was written. I put in a HTTP header to request no caching: <meta http-equiv="Cache-Control" content="no-store" /> The closest thing to a cache that I have configured in Django settings is SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db', no CACHES … -
Model to Insert multiple values for the same field?
The goal is to put multiple status_code and event_code for 1 instruction. So 1 instruction can be associated with one or multiple scrap_code or event_code. But a single scrap_code or event_code cannot have more than 1 instruction. class Instruction(models.Model): name = models.CharField(max_length=100) I have made 2 separate models for scrap_code and event_code class ScrapCodeInstruction(models.Model): scrap_code = models.IntegerField() instruction = models.ForeignKey(Instruction) class EventCodeInstruction(models.Model): event_code = models.IntegerField() instruction = models.ForeignKey(Instruction) I need to register it in admin in the way that for 1 instruction there can be multiple scrap_code or event_code. Also scrap_code(s) and event_code(s) can share the same Instruction. I can use InlineModelAdmin like TabularInline or StackedInline in admin. But it would be great if the values come as comma separated rather than Tabular of Stacked. How can I make it as comma separated in admin?(2nd way to have multiple fields together) -
Django 'trans' Tag: display {% trans 'test' %} instead of test
I try to implement internationalization on my Django project I have installed gettext and run makemessages and compilemessage that create my 2 .po and .mo files base.html {% load static i18n %} {% load static %} test_translation.html {% extends 'layouts/base.html' %} {% load i18n %} ... <h2>{% trans 'test translation' %}</h2> but it does not work as it seem 'trans' tag seem not to be interpreted in fact, browser display {% trans 'test translation' %} (with the bracket and %) instead of test translation -
Consistent Wagtail menus showing parents, children and siblings
I have a simple Wagtail site made of several pages of type HomePage I want use Wagtails in-built menu system for all pages created from the HomePage model and home_page.html template. All the pages have Show in menus: selected. Using this guide here, I have created the following get_context method : class HomePage(Page, Dreamer, Seo): def get_context(self, request): context = super(HomePage, self).get_context(request) context['menuitems'] = self.get_children().filter(live=True, show_in_menus=True) ... and placed the following code in my template : {% for menu in menuitems %} <a class="nav-item nav-link active" href="{{menu.url}}">{{menu.title}}</a> {% endfor %} Other than the root HomePage not showing at all, the menu displays the child pages, until I follow a link to a child page when all the links disappear (because the pages are no longer children). Question: how do I get the menu show the root HomePage and also the child pages even when I am on a sibling, parent or child page? Any help greatly received. -
Endpoints sharing part of an URL
I'm currently building an API and I want to have two viewsets. One related to my User model, and one single route to verify a User email (you POST the currently-valid token to the endpoint). So it looks like this: UserViewSet, which allows POST, GET, PUT, PATCH, DELETE VerifyUserViewSet, which only allows POST In my router, here's my config: router = routers.DefaultRouter() router.register("users", UserViewSet, "users") router.register("users/verify", VerifyUserViewset, "users/verify") My problem is as follows: "users/verify" allows a GET request (when it shouldn't) because it is targeting the "users" endpoint with "request" as the user id. If I change the order in my router, then "users" only accept POST because the endpoints targets "users/verify". This seems to be happening because they share the same url part "users". Is there a way to bypass this behavior so that they don't overlap without changing the endpoints url? Thanks -
automatic field update when GET object is called. is it right and possible? drf
What is the best way to implement the next situation: I need that when some object endpoint is GET called then isCalled change to True. for example when api/objects/1 my model: class Object (models.Model): someObject = models.ForeignKey(User, on_delete=models.CASCADE) isCalled = models.BooleanField(default=False) # dateCalled = models.DateTimeField(auto_now=True, null=True) my views.py: class SingleMessageView(generics.RetrieveUpdateDestroyAPIView): queryset = Message.objects.all() serializer_class = MessageSerializer # def get(self)? : #function to implement the solution should be here? is it possible? what is the most efficient way to implement it and where (views.py/ serializers.py) to put the solution? THANKS!! -
Login with Email and Password in Django
I Want to login using Email and Password in Djnago so I took help from Youtube and Other StackOverflow's answers but It can't work. Problem : I can't find out any problem in my code(given below) but IT IS NOT WORKING!! backends.py(inside 'account' named app) from django.contrib.auth.models import User class EmailBackend(object): def authenticate(self, username=None, password=None, **kwargs): try: user = User.object.get(email=username) except User.DoesNotExist: return None else: if user.check_password(password): return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None views.py(inside 'page' named app) def login(request): if request.method == "POST": email = request.POST['email'] password = request.POST['password'] user = authenticate(username=email, password=password) if user is not None: print("You are Logged in") else: print("Please Enter Valid Email or Password") return render(request, "page/login.html") settings.py AUTHENTICATION_BACKENDS = [ 'account.backends.EmailBackend' ] Note: It works good with default username and password authentication. Please help me to solve this problem.. Thank You!! -
User object .save() does not save after upgrading django 2.1 => 2.2
I am experiencing a very strange bug where I can create and save a User from the django shell, but when I exit and reopen the shell, the User disappears. This is in a prod-like environment with a proper backing DB. The issue goes away if I downgrade Django 2.2 -> 2.1. >>> u = User(id=123131323122, first_name='hi', last_name='sup', email='test@mysupertest.com', birthdate='2000-01-01') >>> u.set_password('foobar') >>> u.save() >>> User.objects.count() 1059790 >>> u.refresh_from_db() >>> u <User: test@mysupertest.com> >>> now exiting InteractiveConsole... myuser$ python manage.py shell Python 3.6.9 (default, Nov 23 2019, 07:02:27) [GCC 6.3.0 20170516] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from mypackage.models import User >>> User.objects.count() 1059789 >>> User.objects.get(email='test@mysupertest.com') Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 408, in get self.model._meta.object_name mypackage.models.User.DoesNotExist: User matching query does not exist. -
Django, add table row using javascript
How to if the teacher select Items (4) using JavaScript, as you can see, the table row adjust, it depends on what Items that the user select, please help me guys here's the example: if the user select Items (3) here is my html <table class="tableattrib" id="myTables"> <tr> <td colspan="1" class="tdhead1">Class</td> <td colspan="20" class="tdcell"> &nbsp;&nbsp; <select> <option>Grading Categories</option> </select>&nbsp;&nbsp; <select onchange="myFunction()"> <option>Items</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select>&nbsp;&nbsp; <select> <option>Section</option> </select> </td> </tr> <tr> <td class="tdnb" colspan="21"><input id="myInput" type="text" placeholder="Search Student" class="search"></td> </tr> <tr> <td colspan="1" class="tdhead">Student Name</td> <td class="tdcell1"><input type="text" name="" id="datepicker" placeholder="mm/dd/yyyy" title="Quiz Date"/></td> <td class="tdcell1"><input type="text" name="" id="datepicker1" placeholder="mm/dd/yyyy" title="Quiz Date"/></td> <td class="tdcell1"><input type="text" name="" id="datepicker2" placeholder="mm/dd/yyyy" title="Quiz Date"/></td> <td class="tdcell2">Average</td> </tr> <tbody id="myTable"> <tr id="myRow"> <td colspan="1" class="tdcell">Marvin Makalintal</td> <td class="tdcell1"><input type="text" name=""/></td> <td class="tdcell1"><input type="text" name=""/></td> <td class="tdcell1"><input type="text" name=""/></td> <td class="tdcell1"><input type="text" name=""/></td> </tr> <tr> <td class="tdbtn" colspan="21"><button type="button" class="save">&plus;&nbsp;Save</button> &nbsp;<button type="button" class="save">&check;&nbsp;Finalize</button></td> </tr> </tbody> </table> </body> <script> function myFunction() { var row = document.getElementById("myRow"); var x = row.insertCell(1); x.innerHTML = "New cell"; } </script> -
Why is VS Code debugger not working for Django mutations?
I'm trying to debug django in VS Code. Breakpoints work when the startup code runs, but when I execute a mutation, it doesn't. Anyone knows why that could be? this is what my configuration file looks like: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Django: Runserver", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", ], "django": true, } ] } Any ideas or pointers are highly appreciated. -
remove % symbol in Django JavaScript Uncaught SyntaxError: Unexpected token ']'
Hi i am a newbie please help. I can't remove this % symbol for high charts to use it, how can i make sure its not a string and just a float WITHOUT THE %. please help series: [{ name:'Top Priority Services', data: [] },{ name:'Central Wiki Service', data: [99.75%] },{ -
django shop, add_to_cart, counter product
I have a big problem. I create a shop without payment support. Only display of ordered products in the administration panel. Each user has a different product price. I would like to add the option to add products to 'Cart'. Product name, product price multiplied by its quantity and total payment. Unfortunately, my code does not work, I'm already slightly lost in it. My file offers/models.py class Product(models.Model): product_name = models.CharField(max_length=100) category = models.CharField(max_length=50) weight = models.FloatField() description = models.TextField(blank=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return self.product_name class UserProduct(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product_name = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.FloatField() is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return str(self.user.username) if self.user.username else '' class OrderProduct(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) quantity = models.IntegerField(default=1) def __str__(self): return str(self.product) if self.product else '' class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) products = models.ManyToManyField(OrderProduct) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def get_total(self): total = 0 for order_product in self.products.all(): total += order_product.get_final_price() return total def __str__(self): return str(self.user.username) if self.user.username else '' And my views.py It's mainly about the function add_to_cart def index(request): context = { …