Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to print multiple values from two lists in django template
I am trying to figure out a way to print values from two different context variables in a single loop. I have tried the zip() method but it does not seem to work and does not print variables on the template. This is how I tried index.html <tbody> {% for item1, item2 in mylist %} <tr> <td><a href="/{{ url.short_url }}">/{{ item1.short_url }}</a></td> <td>{{ item1.original_url }}</td> <td>{{ item1.created_at }}</td> <td>{{ item1.clicks|intcomma }}</td> <td>{{ item2.browser }}</td> <td>{{ item2.platform }}</td> <td><a href="#"> <svg class="octicon octicon-graph" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"> <path fill-rule="evenodd" d="M16 14v1H0V0h1v14h15zM5 13H3V8h2v5zm4 0H7V3h2v10zm4 0h-2V6h2v7z"> </path> </svg> </a></td> </tr> {% endfor %} </tbody> views.py def index(request): urls = Url.objects.order_by('-created_at') clicks = Click.objects.order_by('-created_at') # context = {'urls': urls, 'clicks': clicks} mylist = zip(urls, clicks) context = { 'mylist': mylist, } return render(request, 'heyurl/index.html', context) But on running the local server I don't see anything on the table view. What am I doing wrong here? Are there any alternatives ? Here's my current version of code. models.py from django.db import models class Url(models.Model): short_url = models.CharField(max_length=255) original_url = models.CharField(max_length=255) clicks = models.IntegerField(default=0) created_at = models.DateTimeField('date created', auto_now_add=True) updated_at = models.DateTimeField('date updated', auto_now=True) class Click(models.Model): url = models.ForeignKey(Url, on_delete=models.CASCADE, related_name='related_clicks') browser … -
Invalid default value for 'id' - Django project
When I try to migrate I get this error Invalid default value for 'id' And in my dictionary I have no 'id' fields models.py from django.db import models class Product(models.Model): code=models.SlugField(max_length=70,unique=True) designation=models.CharField(max_length=255) def __str__(self): return self.article.code views.py from .models import Product def viewproduct(request): products={'message':'passe','my_product':[{'code':'mlkk','designation':'toto'}, {'code':'molo','designation':'patate'},...]} all_products=products['my_product'] for product in all_products: object_product=Product(code=product['code'],designation=product['designation']) object_product.save() Noted that my dictionary contains several products -
django 404 error The current path, didn’t match any of these
i have such error, when i try edit or delete: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/edit/ Using the URLconf defined in lab4new.urls, Django tried these URL patterns, in this order: create/ edit/<int:id>/ delete/<int:id>/ The current path, edit/, didn’t match any of these. but i can't get what's wrong with path: that's my urls.py: from django.urls import path from lab4 import views urlpatterns = [ path("", views.index), path("create/", views.create), path("edit/<int:id>/", views.edit), path("delete/<int:id>/", views.delete), ] Create works fine by the way, but what's the problem with edit and delete? -
Django Queryset not working after tranformation to Abstract class child
For more than a year, I construct many of my query using a Django Model where I have simple relation between none abstract model objects and everything was working perfectly : class Taxon(models.Model): parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='children') rank = models.CharField(max_length=200, unique=False, default="NA") name = models.CharField(max_length=200, unique=False, default="NA") class Sequence(models.Model): taxon = models.ForeignKey(Taxon, null=True, blank=True, on_delete=models.CASCADE) amplicon = models.CharField(max_length=1000, unique=False) sequence = models.CharField(max_length=1000, unique=False) score = models.FloatField() Exemple of queryset using my Model : taxon.sequence_set.filter(stuff_filtering) But recently I had to apply some modifications on my database and my Sequence objects are now derivated from an Abstract class called Observation, becoming this class Observation(models.Model): taxon = models.ForeignKey(Taxon, null=True, blank=True, on_delete=models.CASCADE) class Meta: abstract = True class Sequence(Observation): amplicon = models.CharField(max_length=1000, unique=False) sequence = models.CharField(max_length=1000, unique=False) score = models.FloatField() def __str__(self): return str((self.amplicon, self.sequence, self.score, self.taxon)) I didn't changed anything in my queryset because django documentation about abstract class (https://docs.djangoproject.com/en/3.2/topics/db/models/) say you can still use your chlid_set in a query. However i'm facing this error and I couldn't understand why. AttributeError: 'QuerySet' object has no attribute 'sequence_set' Knowing that in case of Abstract base classes, a table should be created in db for each child with parent attribute... So i … -
Serializing Array Field to String
I have an array field in my model i need to serialize and return the first 10 tags from the query getting error while serialising the data. referred - DRF serialize ArrayField as string serializers.py class StringArrayField(ListField): """ String representation of an array field. """ def to_representation(self, obj): obj = super().to_representation(self, obj) # convert list to string return ",".join([str(element) for element in obj]) def to_internal_value(self, data): data = data.split(",") # convert string to list return super().to_internal_value(self, data) class TagsSearchSerializer(serializers.ModelSerializer): tags = StringArrayField() class Meta: model = Mymodel fields = ('id', 'tags') models.py class Mymodel(models.Model): tags = ArrayField(models.CharField(max_length=64, blank=True),default=list, blank=True) views.py class TagsSearchAPIView(APIView): """ Used on dropdown menus to dynamically fetch Tags data """ def get(self, request): queryset = Mymodel.objects.all() tags = queryset.order_by('tags')[:10] serialized_tags = TagsSearchSerializer(tags, many=True, context={'request': request}) results = serialized_tags.data return Response({'results': results}) error to_representation() takes 1 positional argument but 2 were given -
User passes test in django to check subscription
I have a django application where I need to check if a user has a valid subscription, otherwise it redirects the user to his/her dashboard. I was thinking to use the django decorator user_passes_test but I couldn't find a proper way to create the function to check the user. My models for user and subscription are: class CustomUser(AbstractUser): user_type_data = ( ('admin', 'admin'), ('school_admin', 'school_admin'), ('student', 'student'), ) user_type = models.CharField( max_length=20, choices=user_type_data, default='student') address = models.CharField(max_length=500, null=True, blank=True) city = models.CharField(max_length=200, null=True, blank=True) zip_code = models.CharField(max_length=100, null=True, blank=True) country = CountryField(null=True, blank=True) phone = models.CharField(max_length=200, null=True, blank=True) selected_course = models.ForeignKey(QuizTheoryCourse, on_delete=models.CASCADE, null=True, blank=True) class Subscription(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) issue_date = models.DateTimeField(null=True, blank=True) duration = models.IntegerField(choices=DURATION_CHOICES) expiration_date = models.DateTimeField() def __str__(self): return f'{self.user} - {str(self.expiration_date)}' def get_expiration(self): if self.expiration_date: if self.expiration_date > timezone.now(): expiration_date = self.expiration_date + timedelta(days=int(self.duration)) else: expiration_date = dt.now() + timedelta(days=int(self.duration)) else: expiration_date = dt.now() + timedelta(days=int(self.duration)) return expiration_date def is_subscription_valid(self): today = timezone.now() return today < self.expiration_date The function I am using to pass in the decorator is: def subscription_valid(user): try: superuser = user.is_superuser user_valid = user.subscription.is_subscription_valid return superuser or user_valid except user.DoesNotExist: return False My problem is that, anytime the user doesn't have any … -
ImportError: cannot import name 'fromshare' from 'socket'
im facing this error ImportError: cannot import name 'fromshare' from 'socket' (/app/.heroku/python/lib/python3.10/socket.py) File "/app/coreapp/forms.py", line 1, in <module>from socket import fromshare ` im facing this error ImportError: cannot import name 'fromshare' from 'socket' (/app/.heroku/python/lib/python3.10/socket.py) File "/app/coreapp/forms.py", line 1, in <module>from socket import fromshare` #i was trying to run Heroku run python manage.py migrate #my forms file : from django import forms from django.contrib.auth.models import User from coreapp.models import Restaurant from django.db import models class UserForm(forms.ModelForm): email = forms.CharField(max_length=100, required=True) password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ("username", "password", "first_name", "last_name", "email") class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant fields = ("name", "phone", "address", "logo") ``` ` File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() … -
Value: "" must be an instance of <class 'dict'> in django, djongo
I am using Django and connecting with a mongodb database using djongo. My database requirements are such that I need to use an embedded field in one of the collections. On adding any entry on Django Admin I am getting a preview error - I have 2 models, City containing 3 fields, and the Address containing 2 fields a city object and a pincode. Hence the city is an embedded field in model Address. On adding this entry through django-admin an error message pops up, and the entry doesn't get saved in the database. Please correct the error below -> Value: gwalior-MP-India must be an instance of <class 'dict'> An entry in address table looks like - { "city": { "city":"gwalior", "state":"MP", "country":"India" }, "pincode":"9999" } P.S. - I was not able to attach the screenshot of django-admin panel, as I was getting an error while posting this question -> Failed to upload image; an error occurred on the server. Here are the code snippets and the versions of the installed packages. models.py class City(models.Model): _id = models.ObjectIdField() city = models.CharField(db_column='city', max_length=255, null=True, blank=True) state = models.CharField(db_column='state', max_length=255, null=True, blank=True) country = models.CharField(db_column='country', max_length=255, null=True, blank=True) def __str__(self): return self.city … -
How to extracting long views code block in a smaller method?
I have a Django application. And I have a long method where a user can upload a file and the content of the file will be shown in textarea. Because of the S.O.L.I.D principle. The code that is responsible for extracting the data from the file has to be in a seperate method. So this is the views.py: class ReadingFile(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", { "form": form }) def extractingtextfromimage(): pass def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) content = '' if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) name_of_file = str(request.FILES['upload_file']) uploadfile.save() print('path of the file is:::', uploadfile.image.name) with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r') as f: print("Now its type is ", type(name_of_file)) print(uploadfile.image.path) # reading PDF file if name_of_file.endswith('.pdf'): pdfFile = wi(filename= uploadfile.image.path , resolution=300) text_factuur_verdi = [] image = pdfFile.convert('jpeg') imageBlobs = [] for img in image.sequence: imgPage = wi(image=img) imageBlobs.append(imgPage.make_blob('jpeg')) for imgBlob in imageBlobs: image = Image.open(io.BytesIO(imgBlob)) text = pytesseract.image_to_string(image, lang='eng') text_factuur_verdi.append(text) content = text_factuur_verdi print(text_factuur_verdi) # ENDING Reading pdf file else: content = f.read() print(content) return render(request, "main/create_profile.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/create_profile.html", { "form": submitted_form, }) And it is about the comment: reading PDF file till: # ENDING Reading pdf file … -
How change fields helptext style django?
I want change text color etc of help_text in fields models. I see in html that there is helptext class: <span class="helptext">Sentenses</span> so I try in my css file: .helptext { color: #bd512f; } and it dont do changes. Is there collision with bootstrap? -
context must be a dict rather than type
I've been working on a project for a while, and I have a resource called Item. The item detail view can only be viewed, if the item is from the same company as the user. If not, it should be a 404. This is the code that I have: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # To only show items in your company if (context['item'].company != getCompany(self.request.user)): return HttpResponseNotFound return context getCompany is a function I wrote to check the users company. The company is in a custom Profile model. This function works, I already used it multiple times for other things Now i expected to have a 404 when going to a item from another company, but instead this error appears: Internal Server Error: /fr/items/5/ Traceback (most recent call last): File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/template/response.py", line 92, in rendered_content return template.render(context, self._request) File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/template/backends/django.py", line 58, in render context = make_context( File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/template/context.py", line 278, in make_context raise TypeError( TypeError: context must be a dict rather than type. Edited: What did I miss? -
Django, check django.db.Model subclass implementation
I am creating a subclass of Django's Model class, and require the user to implement some attributes and methods. I did it by inheriting from ABC from django.db.models.base import ModelBase class AbstractFooMeta(ModelBase, ABCMeta): """To avoid metaclass conflicts""" class AbstractFoo(ABC, models.Model, metaclass=AbstractUploadMeta): my_num: int magic_string: str name = models.CharField(max_length=250) class Meta: abstract = True @abstractmethod def do_thing(self): pass @classmethod @abstractmethod def do_class_thing(cls): pass class AbstractMagicFoo(AbstractFoo): magic_str = "answer is 42" class Foo(AbstractMagicFoo): my_num = 7 def do_thing(self) -> str: print('did the thing') @classmethod def do_class_thing(cls) -> str: print('did the class thing') I can create the migration, but when I try to run the migration I get: File "/home/michael/.venv/project/lib/python3.9/site-packages/django/db/migrations/state.py", line 362, in reload_model self._reload(related_models) File "/home/michael/.venv/project/lib/python3.9/site-packages/django/db/migrations/state.py", line 395, in _reload self.apps.render_multiple(states_to_be_rendered) File "/home/michael/.venv/project/lib/python3.9/site-packages/django/db/migrations/state.py", line 597, in render_multiple model.render(self) File "/home/michael/.venv/project/lib/python3.9/site-packages/django/db/migrations/state.py", line 872, in render return type(self.name, bases, body) TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases I am guessing Django is not using the meta class I defined. I tried setting the metaclass on all child classes but did not help. How can I attach some logic to AbstractFoo that when a concrete class (i.e. not AbstractMagicFoo, but only … -
DRF: How can I show all fields of a m2m field instead of just the name
I'm building a simple Lead Generator using Django Rest Framework. I'm trying to show a list of "assigned facilities" inside a lead using django's many to many fields. But all it will show inside the API is the id of each of the facilities associated to the many to many field. How do I access more than just the name using DRF? I basically need to show the name, a description and a picture of the facility from each facility record. serializers.py class LeadUpdateSerializer(serializers.ModelSerializer): is_owner = serializers.SerializerMethodField() class Meta: model = Lead fields = ( "id", "first_name", "last_name", "PrimaryAddress", "assigned_facilities", ) read_only_fields = ("id", "is_owner") def get_is_owner(self, obj): user = self.context["request"].user return obj.agent == user models.py class Facility(models.Model): UUID = models.CharField(max_length=150, null=True, blank=True) Name = models.CharField(max_length=150, null=True, blank=False) mainimage = models.ImageField(null=True, blank=True) FacilityDescription = models.TextField(max_length=1000, null=True, blank=True) def __str__(self): return self.Name class Lead(models.Model): assigned_facilities = models.ManyToManyField(Facility, related_name='assigned_facilities') created_at = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=40, null=True, blank=True) last_name = models.CharField(max_length=40, null=True, blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" -
How to run Django rest api and react build together
I'm running django rest api and react in 2 different ports (using nginx and gunicorn), I want to only run the django server that will take charge of showing react build (react pages), so both react and django will run in the same port. -
issue with connecting to PostrgreSQL on localhost in Django application [duplicate]
I am using Docker to run my Django app and I have multiple images in it: PostgreSQL, celery_worker, celery_beat, and django_app. All of them except celery_beat is working fine. I am using this command to build docker: docker-compose -f docker-compose.yml up -d --build When I open Docker Desktop I see that it restarts all images, everything is working fine for few seconds, then it exits celery-beat and returns in celery-beat image with the following error: [2022-10-13 15:34:59,440: WARNING/MainProcess] could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? I tried many solutions that I found on StackOverflow and other pages but with no success. 4 out of 5 images are working fine. When clicking on postgreSQL image I see the following status: 2022-10-13 13:27:04.195 UTC [1] LOG: database system is ready to accept connections docker-compose.yml version: '3.8' services: db: image: postgres:14.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=PF23_admin - POSTGRES_DB=postgres container_name: docerized_app_db_postgresql_dev app: build: context: ./backend dockerfile: Dockerfile restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./backend/:/usr/src/backend/ ports: - 8000:8000 env_file: - ./.env depends_on: - db container_name: docerized_app_django_app_dev redis: image: redis:7-alpine ports: - "6379:6379" container_name: docerized_app_redis_dev celery_worker: … -
Code works without errors in vs code, but not from command promt
I am learning django and to run a server i should do python manage.py runserver. I have installed django, but when i try to run a command through a command prompt i always get an error Traceback (most recent call last): File "D:\projects\django-proj\password_generator\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\projects\django-proj\password_generator\manage.py", line 22, in <module> main() File "D:\projects\django-proj\password_generator\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? if i call django-admin in command prompt, it works well. it also works if i just run a code in vs code. what can be the problem? -
Using HTMX/Javascript in Django Template : not defined
I decided to try HTMX with Django and implementing a Django form in a modal box. I found this tutorial and was following it. I got to the part where it uses an HTMX function htmx:afterSwap to open the modal but when I put that in a script tag in the template, I run into an error. It is Step 4 where the error occurs. My template looks (mostly) like this. I've tried to trim it down to the essentials. {% for thing in things %} {% if forloop.first %} <ul id="myThingList" class="things"> {% endif %} <button id="thing{{ thing.id }}Button" type="button" class="btn btn-primary" hx-get="{% url 'myapp:things-create' %}" hx-target="#thingSection"> Upload Thing</button> <li id="thingItem" class="thing" hx-target="this" hx-swap="outerHTML"> {{ thing.name }} </li> <div id="thingModal" class="modal fade" role="dialog" tabindex="-1" aria-labelledby="thingModal" aria-hidden="true"> <div id="thingSection" class="modal-dialog modal-dialog-centered" hx-target="this" role="document"></div> </div> {% if forloop.last %} </ul> {% endif %} {% empty %} <p class="no-things">No things have been added yet.</p> {% endfor %} <script> const modal = new bootstrap.Modal(document.getElementById("thingModal")) htmx.on("htmx:afterSwap", (e) => { // Response targeting #thingSection => show the modal if (e.detail.target.id == "thingSection") { modal.show() } }) </script> I am getting Uncaught ReferenceError: bootstrap is not defined Additional information: HTMX works (I use it in other … -
(urls.E004). Your URL Pattern is invalid in project level urls.py file
I am newbie to Django. I am getting the below error in-spite of rightly mapping the app level urls.py file to project level urls.py. Please help. urlpatterns = [ path('admin/', admin.site.urls), path('app_space/', include ('app_space.urls')) ] Response in terminal: SystemCheckError: System check identified some issues: ERRORS: ?: (urls.E004) Your URL pattern <contextlib._GeneratorContextManager object at 0x000001C33030C7C8> is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. -
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request
I'm trying to do get-request from react to django-server let projects = await axios.get('http://127.0.0.1:8000/api/project', {headers}).catch(error => console.log(error)) And i get 'Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/project' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.' -
how do I convert PCM 16bit signed LE 16000kHz to WAV in python given only the bytes?
I pulled an object from amazon s3 buckets like so: s3_response_object = S3.get_object(Bucket=bucket_name, Key=key_name) object_content = s3_response_object['Body'].read() # object content --> b'\x06\x10...' Inside the bucket you have a PCM 16bit signed LE 16000kHz audio file. If you write that file to a .wav file like so: with open("audio.wav", "wb") as f: f.write() The wav file cannot be played by quicktime VLC or any audio player. How can I convert these bytes into a wav file. The end goal is to pass these bytes into a view with django, and I have already verified that my django view works properly using a drop in replacement stream of bytes to use for the view, and the audio plays back no problem. I think the bytes that I get from AWS need some type of conversion to be valid for passing into my view. Any help would be much appreciated. END GOAL INSIDE DJANGO VIEW: def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: """" get_context_data gets audio from S3 and pass to django view""" context = super().get_context_data(**kwargs) s3_response_object = S3.get_object(Bucket=bucket_name, Key=key_name) object_content = s3_response_object['Body'].read() context["audio"] = b64encode(object_content) return context INSIDE DJANGO TEMPLATE <audio controls> <source src="data:audio/wav;base64,{{ audio }}" type="audio/wav"> </audio> Any help would be … -
AttributeError at /customers/f0e85ace-438f-4c61-a129-6d5986e6f346/ 'customer' object has no attribute 'get'
i have just started django and i am struggling to find error .Seems like get() method is not being recognized .What should i do?I would really appreciate your help from django.db import models from django.core.validators import RegexValidator import uuid # Create your models here. class customer(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4) name=models.CharField(max_length=200,null=True) phone_no=models.CharField(max_length=200, validators= [RegexValidator(r'^\d{1,10}$')],null=True) email=models.EmailField(max_length=200,null=True) def __str__(self): return self.name class tag(models.Model): name=models.CharField(max_length=200,null=True) def __str__(self): return self.name class products(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4) categories=[ ('organic','organic'), ('inorganic','inorganic') ] name=models.CharField(max_length=200,null=True) price=models.FloatField(null=True) manufacturedate=models.DateTimeField(auto_now_add=True,null=True) description:models.TextField(null=True) categories=models.CharField(max_length=200,null=True,choices=categories) tag=models.ManyToManyField(tag) def __str__(self): return self.name class order(models.Model): id=models.UUIDField(primary_key=True,default=uuid.uuid4) status=[ ('pending','pending'), ('out of stock','out of stock',), ('Delivered',('Delivered')) ] ordered_date=models.DateTimeField(auto_now_add=True) status=models.CharField(max_length=200,null=True,choices=status) customer=models.ForeignKey(customer,null=True,on_delete=models.SET_NULL) product=models.ForeignKey(products,null=True,on_delete=models.SET_NULL) urls.py url seems ok i could not find any mistake from django.urls import path from . import views urlpatterns=[ path('',views.home), path('products/',views.product), path('customers/<str:pk>/',views.customer), ] views.py Here in the customer it is not it says get is not the attribute .seems like i am missing something from django.shortcuts import render from .models import * # Create your views here. def home(request): customers=customer.objects.all() orders=order.objects.all() total_customers=customers.count() total_orders=orders.count() delivered=orders.filter(status='Delivered').count() pending=orders.filter(status='pending').count() context={'customers':customers,'orders':orders,'total_customers':total_customers, 'total_orders':total_orders,'delivered':delivered, 'pending':pending } return render(request,'accounts/home.html',context) def product(request): product=product return render(request,'accounts/products.html') def Customer(request,pk): Customer=customer.objects.get(id=pk) return render(request,'accounts/customers.html') -
Should I use Django Function based views or Class based views for better functionality?
I am just learning Django, and I am attempting a project to create a notes app. During the process of the project, a friend of mine advised me to use function-based views, but I later discovered that class-based views can be customized too. Given that both can work fine for my little project, is it best practice to use function-based views from scratch or to override class-based views methods? Thank you. -
Django Browser back button issue after logout not able to login again
I am trying to integrate Azure AD with Django and achieve single page application behaviour.When I login with Azure ad at first time it working fine, i logout and click Browser Back button from Logout page it is stay on logout page but After that i'm try to login from logout page I'm not able to login again. Index content doesn’t load, content remains same as logout page. -
how to clear an input fields when i click another tab it should clear the input field data Any suggestions?
any suggestions Iam working on one data filtering part in my task it takes an input values it shows filter options but if i open another tab of same page or switched to another page still it holds given input values my motto is clear the screen when we click another page or tab any suggestions please????? -
How to call bussines logic from seperate class in view in Django?
I am using django framework. And I have some functionality for uploading files. And I have a textarea where the extracted content of the uploaded file will be shown. So for example if you upload a pdf file within a image that contains text. In the textarea the text will be shown. But the logic for extracting the text from the image of course doesn't belong too the method in the view. So I made a seperate class for it, with name: extractingTextFromFile.py that looks like this: import io from tracemalloc import start from PIL import Image import pytesseract from wand.image import Image as wi import re class ExtractingTextFromFile: def extractingtextfromimage(): text_factuur_verdi = [] #image = pdfFile.convert('jpeg') imageBlobs = [] for img in image.sequence: imgPage = wi(image=img) imageBlobs.append(imgPage.make_blob('jpeg')) for imgBlob in imageBlobs: image = Image.open(io.BytesIO(imgBlob)) text = pytesseract.image_to_string(image, lang='eng') text_factuur_verdi.append(text) and I have the views.py: from django.shortcuts import render from django.views import View from django.http import HttpResponseRedirect from .forms import ProfileForm from .models import UploadFile import extractingTextFromFile as textFromFile from wand.image import Image as wi from PIL import Image import pytesseract from django.conf import settings import io import os class ReadingFile(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", …