Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I set up Postgresql on Django Heroku?
Can someone please provide steps on how to set up a postgresql database to connect to my site? I have a model that I need to create "instances" of. I need them to stay. I was told I need to use a database. I'm having trouble figuring out the right way to set it up. -
Django Rest Framework won't serialize GeoJSON properly
I am trying to calculate a polygon based on latitude/longitude of center point, radius, and number of sides in Django Rest Framework to expose an API. I have it mostly working, but the serializer doesn't convert the property model into a geoJSON properly. I have included my code below Serializer.py from rest_framework import serializers from django.core.serializers import serialize from .models import Circle from rest_framework_gis.serializers import GeoFeatureModelSerializer class CircleSerializer(GeoFeatureModelSerializer): class Meta: model = Circle fields = ('lat', 'lng', 'radius', 'resolution', 'id', 'polygon') geo_field = 'polygon' Views.py from django.shortcuts import render from rest_framework import viewsets from .serializers import CircleSerializer from .models import Circle from django.core.serializers import serialize from django.http import HttpResponse # Create your views here. class CircleViewSet(viewsets.ModelViewSet): queryset = Circle.objects.all().order_by('id') serializer_class = CircleSerializer urls.py from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'Circle', views.CircleViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] models.py # from django.db import models from django.core.validators import MinValueValidator from django.contrib.gis.db import models from django.contrib.gis.geos import Point import math import decimal # Create your models here. class Circle(models.Model): lat = models.DecimalField(max_digits=10, decimal_places=8) lng = models.DecimalField(max_digits=11, decimal_places=8) radius = models.DecimalField(max_digits=14, decimal_places=8) resolution = models.PositiveIntegerField(validators=[MinValueValidator(3)]) id = models.CharField(max_length=6, primary_key=True) polygon = … -
why do i keep getting this error( Field 'id' expected a number but got ''. ) each time users like a post from their own timeline?
Here is the users account view that i want users to be able to like their post from, it has really been a challenge to get my head around this. would appreciate some help. def account_view(request, *args, **kwargs): """ - Logic here is kind of tricky is_self is_friend -1: NO_REQUEST_SENT 0: THEM_SENT_TO_YOU 1: YOU_SENT_TO_THEM """ context = {} user_id = kwargs.get("user_id") try: account = User.objects.get(pk=user_id) except: return HttpResponse("Something went wrong.") if account: context['id'] = account.id context['username'] = account.username context['bio'] = account.bio context['get_full_name'] = account.get_full_name context['email'] = account.email context['profile_pic'] = account.profile_pic.url context['cover_image'] = account.cover_image.url context['city'] = account.city context['country'] = account.country context['gender'] = account.gender context['hide_email'] = account.hide_email post_id = request.GET.get("likeId", "") try: post_id = Post.objects.get(pk=post_id) except Post.DoesNotExist: liked= False like = Like.objects.filter(user=user, post=post) try: post_list = Post.objects.filter(user_name=account) except Post.DoesNotExist: post_list = Post(user_name=account) save.post_list() posts = post_list.all() context['posts'] = posts Here is my like view, how best do can i accomplish users and friends being able to like their post from their own profile or timeline ? def like(request): post_id = request.GET.get("likeId", "") user = request.user post = Post.objects.get(pk=post_id) liked= False like = Like.objects.filter(user=user, post=post) if like: like.delete() else: liked = True Like.objects.create(user=user, post=post) resp = { 'liked':liked } response = json.dumps(resp) return … -
Problem in embedding an IDE to my website
I've been watching youtube videos on embedding the repl.it IDE to my website. The problem is, in the repl.it IDE, the save option is not available and let alone the copy embed code is also not available. I am in urgent need of an IDE like repl.it, progamiz, etc for my website. Any solution is appreciated. I've tried almost all the online IDEs so far. -
How to start a Dockernized Django server with custom ip address?
When we want to run a bare Django app we use the term: python manage.py runserver <ip>:<port> to start a web server with the desired IP address. I tried to do a similar thing with Docker and Django inside the docker-compose file: version: '3.1' volumes: init-db: data-db: services: mongo: image: mongo restart: always environment: MONGO_INITDB_ROOT_USERNAME: <name> MONGO_INITDB_ROOT_PASSWORD: <password> ports: - 27020:27020 command: mongod --quiet --logpath /dev/null splash: image: scrapinghub/splash ports: - "8050:8050" restart: always web: build: . restart: unless-stopped command: > bash -c "pip install -r requirements.txt && python manage.py makemigrations && python manage.py migrate && python manage.py runserver <some_ip>:<some_port>" tty: true volumes: - .:/usr/src/app ports: - 8000:8000 depends_on: - mongo Now after running it is giving me web_1 | Error: That IP address can't be assigned to. -
Can't get proper response from `issubclass()` when called with Django's `__fake__` model type inside migration
I'm trying to generate UUIDs for some models in a migration. The problem is that the models returned from apps.get_app_config(app_name).get_models() are these __fake__ objects, they are what Django calls historical models, so calling issubclass(fake_model, UUIDModelMixin) returns False when I am expecting True. Is there anyway to determine what parent classes these historical model objects actually inherited from? Relevant Django docs: https://docs.djangoproject.com/en/3.1/topics/migrations/#historical-models And here is the full function being called in a migration: from os.path import basename, dirname import uuid from common.models.uuid_mixin import UUIDModelMixin def gen_uuid(apps, schema_editor): app_name = basename(dirname(dirname(__file__))) models = apps.get_app_config(app_name).get_models() uuid_models = [m for m in models if issubclass(m, UUIDModelMixin)] for model in uuid_models: for row in model.objects.all(): row.uuid = uuid.uuid4() row.save(update_fields=['uuid']) -
How to choose appreciate AWS EC2 instance
I want to deploy a website that uses Django on the server side and reactJs Frontend on AWS. I'm estimating traffic of about 40,000 per month. It happens that Amazon has several hosting packages. I like the EC2 instances but I don't know which particular instance that'll be suitable for me and being cost effective. I want to host for 6 months to get to understand the platform and later extends it if I'm comfortable with their services. The database isn't that robust. I'll also like to add updates at least two times a week. Honestly, I haven't used AWS before and I don't even know if EC2 is the best for my project. Which of the packages will be best for my project? -
Using integers and strings together in Django choice field
I am trying to use the new Enum types in the latest Django version for the choice field. Specifically I am trying to store the various states of United States as follows: class States(models.TextChoices): ALABAMA = 'AL', 'Alabama' ALASKA = 'AK', 'Alaska' ..... ..... WISCONSIN = 'WI', 'Wisconsin' WYOMING = 'WY', 'Wyoming' class PersonalInfo(models.Model): state = models.CharField(max_length=2, choices=States.choices, default=States.ALABAMA) Works as expected. Now, I am also trying to make the max_length variable also a class attribute of the choice class to make the code more modular by doing the following: class States(models.TextChoices): ALABAMA = 'AL', 'Alabama' ALASKA = 'AK', 'Alaska' ..... ..... WISCONSIN = 'WI', 'Wisconsin' WYOMING = 'WY', 'Wyoming' MAX_LENGTH = 2 class PersonalInfo(models.Model): state = models.CharField(max_length=States.MAX_LENGTH, choices=States.choices, default=States.ALABAMA) This gives me an error as follows: if self.max_length is not None and choice_max_length > self.max_length: TypeError: '>' not supported between instances of 'int' and 'States' I understand that Django also provides an alternative IntegerChoices for integer but how do I use both text and integer choices together. -
Can't serialize foreignKey object data
I have one-to-many relation Developer and Constructions I want to serialize all Developer field when I serialize Construction object For request { "developer": 1, "name": "as2", "address": "ZZZZZZZZZZZZZsdf", "deadline": "2020-05-13 14:26:58", "coordinates": { "latitude": 49.8782482189424, "longitude": 24.452545489 } } I have an error: { "developer_data": [ "This field is required." ] } It's strange for me because developer_data marked as read_only How can I fix the error? I thin that problem deals with serializer models.py class Developer(models.Model): name = models.CharField(max_length=100) ... def name_image(instance, filename): return '/'.join(['images', str(instance.name), filename]) class Construction(models.Model): developer = models.ForeignKey( Developer, related_name="constructions", on_delete=models.CASCADE ) name = models.CharField(max_length=100) image = models.ImageField(upload_to=name_image, blank=True, null=True) ... serializers.py class DeveloperSerializer(serializers.ModelSerializer): constructions_number = serializers.SerializerMethodField() workers_number = serializers.SerializerMethodField() machines_number = serializers.SerializerMethodField() class Meta: model = Developer fields = ('id', 'name', ...) def create(self, validated_data): instance = super().create(validated_data=validated_data) return instance class ConstructionSerializer(serializers.ModelSerializer): coordinates = PointField() deadline = serializers.DateTimeField(format=TIME_FORMAT) cameras_number = serializers.SerializerMethodField() developer_data = DeveloperSerializer() class Meta: model = Construction fields = ( 'id', 'developer', 'developer_data', 'name', 'image', 'address', 'coordinates', 'deadline', 'workers_number', 'machines_number', 'cameras_number', ) read_only_fields = ('workers_number', 'machines_number', 'cameras_number', 'developer_data') def create(self, validated_data): instance = super().create(validated_data=validated_data) return instance def get_cameras_number(self, obj): return obj.cameras.count() I use standard ModelViewSet for the models in views.py and i … -
```AttributeError: 'Settings' object has no attribute 'FILE_CHARSET'```deployment error
AttributeError: 'Settings' object has no attribute 'FILE_CHARSET' trying to delov my project of Heroku but getting error -
django: problems refering to model primary key in templates (pk)
I am trying to pass the primary keys of a model through various templates and it seems like refering to model primary key as pk does not work. After reading the doc, it seems that the primary key of a model can always be refered as pk. Here is how I set things up: model.py class Products(models.Model): ProductName = models.CharField(max_length=100, primary_key=True) ProductUnit = models.CharField(max_length=100, default="NA") ProductCategory = models.CharField(max_length=100) ProductTagNumber = models.IntegerField(max_length=100) StockOnHand = models.FloatField(max_length=100) views.py def ProductsView(request): queryset = Products.objects.all() products_list = list(queryset) request.session['context'] = products_list return render(request, 'inventory.html', {'products_list':products_list}) def UpdateProductView(request,pk): Product = get_object_or_404(Products, pk=pk) if request.method == 'POST': form = UpdateProductForm(request.POST, instance = Product) if form.is_valid(): form.save() Name = form.cleaned_data.get('ProductName') Category = form.cleaned_data.get('ProductCategory') OH = form.cleaned_data.get('StockOnHand') update1 = Products.objects.filter(pk = pk).update(ProductName = Name) update2 = Products.objects.filter(pk = pk).update(ProductCategory = Category) update3 = Products.objects.filter(pk = pk).update(StockOnHand = OH) messages.success(request, "Changed in Product successfully recorded") return redirect('https://www.allelegroup.exostock.net/inventory.html') else: form = UpdateProductForm(initial = { 'Name' : Products.ProductName, 'Category' : Products.ProductCategory, 'OH' : Products.StockOnHand}, instance =Product) return render(request, 'update_product.html', {'form' : form}) urls.py path('inventory.html', ProductsView, name="inventory"), path('update_product/<int:pk>', UpdateProductView, name="update_product"), inventory.html <tbody style="background-color: white"> {% for Product in products_list %} <tr> <td>{{ Product.pk }}</td> <td>{{ Product.ProductCategory }}</td> <td>{{ Product.ProductTagNumber }}</td> <td>{{ Product.StockOnHand }}</td> … -
Django/Graphene seems to clean database between individual tests in a test run
I'm testing Django/Graphene to see if it can fulfill what I need, but I'm getting trouble in unit testing. I'm using the in-memory SQLite db, with the following code (tests.py): import json from graphene_django.utils.testing import GraphQLTestCase from graphene.test import Client from users.schema import UserType class APITestCase(GraphQLTestCase): def test01_query_users(self): print("Running test01_query_users") response = self.query( ''' query { users { id username email } } ''' ) print (response) content = json.loads(response.content) self.assertResponseNoErrors(response) print (content) assert content == { "data": { "users": [] } } def test02_mutation_addUser(self): print("Running test02_mutation_addUser") response = self.query( ''' mutation { createUser (username: "testuser", email: "testemail@testserver.com", password: "123456") { user { id username email } } } ''' ) print (response) content = json.loads(response.content) self.assertResponseNoErrors(response) print (content) assert content == { "data": { "createUser": { "user": { "id": "1", "username": "testuser", "email": "testemail@testserver.com" } } } } def test03_mutation_addUser(self): print("Running test03_mutation_addUser") response = self.query( ''' mutation { createUser (username: "testuser2", email: "testemail2@testserver.com", password: "123456") { user { id username email } } } ''' ) print (response) content = json.loads(response.content) self.assertResponseNoErrors(response) print (content) assert content == { "data": { "createUser": { "user": { "id": "2", "username": "testuser2", "email": "testemail2@testserver.com" } } } } def test04_query_users(self): print("Running test04_query_users") response … -
Django StaticLiveServerTestCase together with compressed hypertables
I am testing my django 2.2 application using StaticLiveServerTestCase. My database includes several compressed hypertables with foreign key relations i.e.: class Measurement(models.Model): pass class Sensor(models.Model): sensor = models.ForeignKey(Measurement, ...) class SensorResults(models.Model): results = models.ForeignKey(Sensor, ...) The timescaledb specific migration adaptation looks like migrations.RunSQL("SELECT create_hypertable('proj_sensorresults', 'time');"), migrations.RunSQL("ALTER TABLE proj_sensorresults SET (timescaledb.compress, timescaledb.compress_segmentby = 'results_id');"), migrations.RunSQL("SELECT add_compress_chunks_policy('proj_sensorresults', INTERVAL '1 days');"), When tearing down the test database the following error occures: psycopg2.errors.FeatureNotSupported: cannot truncate a table referenced in a foreign key constraint DETAIL: Table "_compressed_hypertable_2" references "proj_sensor". HINT: Truncate table "_compressed_hypertable_2" at the same time, or use TRUNCATE ... CASCADE. I overrode sqlflush to include cascading, I manually truncated and dropped tables, I tried to decompress all hypertables before calling tear down and finally ended up disabling compression. Since my software will be used in the field with very limited bug fixing and updating possible I really do not want to run tests against a modified data base. I am pretty much out of ideas how to achieve this and really would appreciate your ideas! -
How to prevent changing slug value when updating the post if the title has not changed?
I have a purpose about learning django and rest framework. So I faced a problem when I worked on a tutorial project. The slug value changing every time when the article object updating. If the title value has not changed, I want the slug value not to change either. How can I handle this process? For example: When I update article but I haven't made any changes to the title field, the slug value also changes. before update "title" : "article 1", "slug" : "article-1", after update "title" : "article 1", "slug" : "article-1-1", models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) title = models.CharField(max_length=120) content = models.TextField() draft = models.BooleanField(default=False) # taslağa kaydetme işlemi created = models.DateTimeField(editable=False) modified = models.DateTimeField() slug = models.SlugField(unique=True, max_length=150, editable=False) image = models.ImageField( upload_to="media/post/%Y/%m/%d/", blank=True, null=True) modified_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="modified_by") def __str__(self): return self.title def get_slug(self): slug = slugify(self.title.replace("ı", "i")) unique = slug number = 1 while Post.objects.filter(slug=unique).exists(): unique = '{}-{}'.format(slug, number) number += 1 return unique def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() self.modified = timezone.now() self.slug = self.get_slug() return super(Post, self).save(*args, **kwargs) serializers.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ["user", "title", "content", "created", "modified", … -
How can I dispatch URLs in the form sitename.com/<slug>/<slug> in django?
I am trying to create a website whose structure is something like this: A main page with various links of similar kind (like a blog). User can click on any on those and go inside any of them (link will be like site.com/slug). Then again the same thing (this time the link will be like site.com/slug/slug). individual_question.html <div id="argument_container"> {% for argument in argument%} <h6 id='{{ argument.argument_faction }}' style="display:none"><a href=" {{question.get_absolute_url}}{{argument.get_absolute_url}} " style="text-decoration: none; color: black">{{ argument.argument_text }}</a> <br><br> <button type="button" class="btn btn-outline-success btn-sm"><i class="fa fa-thumbs-o-down" style="padding-right: 3px;"></i>Agree</button> <button type="button" class="btn btn-outline-danger btn-sm"><i class="fa fa-thumbs-o-up" style="padding-right: 3px;"></i>Disagree and debate</button> </h6> {% endfor %} </div> urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', home_screen_view, name="home"), path('register/', registration_view, name="register"), path('logout/', logout_view, name="logout"), path('login/', login_view, name="login"), path('account/', account_view, name="account"), path('<slug:question>', individual_question_view, name="individual_question_view"), # for testing path('<slug:argument>', individual_argument_view, name="individual_argument_view"), models.py class Faction(models.Model): faction_id = models.BigAutoField(primary_key=True) faction_question = models.ForeignKey(Question, on_delete=models.CASCADE) faction_name = models.CharField(max_length=30) def __str__(self): return self.faction_name class FactionArgument(models.Model): argument_id = models.BigAutoField(primary_key=True) argument_faction = models.ForeignKey(Faction, on_delete=models.CASCADE) argument_question = models.ForeignKey(Question, on_delete=models.CASCADE, null=True) argument_slug = models.SlugField(max_length=80, null=True) argument_text = models.TextField() user_id = models.ForeignKey(Account, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('individual_argument_view', args=[self.argument_slug]) # chances of error def __str__(self): return self.argument_text views.py def individual_question_view(request, question): context={} question = get_object_or_404(Question, … -
How to access a file object from a CBV that delivers it as a response
I am using Django-WeasyPrint to generate PDF files from HTML templates: from django_weasyprint import WeasyTemplateResponseMixin class MyModelView(DetailView): # vanilla Django DetailView model = MyModel template_name = 'mymodel.html' class PDFDownload(WeasyTemplateResponseMixin, MyModelView): # View that returns the PDF file as a download to the user def get_pdf_filename(self): return 'mypdf - {at}.pdf'.format( at=timezone.now().strftime('%H%M-%d%m%Y'), ) How can I access the file returned in the response as an object? E.g: my_pdf = HttpResponse(reverse( 'pdf_download', kwargs={'id': self.object.id}) -
Django ModuleNotFoundError: No module named "project_name"
when I try to run server I get this error File "/home/mori/Documents/Django/news/articles/admin.py", line 1, in <module> from news.articles.models import Article ModuleNotFoundError: No module named 'news' -
How to associate specific page id with forms to submit POST REQUEST?
Background I have created an small app that can add projects, and show it in the index page, all those projects can be access individualy to its own "profile proJect page" clicking on the project name. Inside the project's profile page, it can be seeing data as ProjectName, ResponsableName, Description and so on. Problem I'd like to add additional information to its project profile page such as financial aid amount, expected revenue,etc. So I have created the respective HTML Forms for each kind of information I need to submit, but I don't have idea how to associate the form with specific project_id. I'd be glad if you could provide me an example about it Project index Project Profile Page Financial aid form in case you click on "Agregar información" views.py def financiamiento(request): if request.method == 'POST': MontoProyecto = request.POST.get('MontoProyecto') MontoPropio = request.POST.get('MontoPropio') MontoBanca = request.POST.get('MontoBanca') MontoPublico = request.POST.get('MontoPublico') Financiamiento.objects.create(MontoProyecto=MontoProyecto, MontoPropio=MontoPropio, MontoBanca=MontoBanca, MontoPublico=MontoPublico) return redirect("/Portafolio") return render (request, "Portafolio/Financiamiento.html") -
nested_data ORM django problem in nested data
[ { "id": 10, "username": "naresh90", "notess": [ { "id": 8, "note": "hello world" }, { "id":9, "note":"hello world 2" } ] } ] how can i acces the notess data only, on screen.... in django... like, [ { "id": 8, "note": "hello world" }, { "id":9, "note":"hello world 2" } ] My views.py... @api_view(["POST","GET"]) def Note_retrive(request,username): if request.method=="POST": serializer=user_all_dataSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) elif request.method=="GET": dts=notes_user.objects.filter(username=username) serializer=user_all_dataSerializers(dts,context={'request': request} ,many=True) return Response(serializer.data) -
Django template rendering slowly
I'm rendering a template and it's taking anywhere between 2-3 seconds to do it. There are quite a few elements on the page (10k checkboxes) and I'm wondering if anyone knows any helpful tricks to cut down on load time. Is it database hits? After inspecting my django connections and profiling, I'm only making two database calls as far as I can tell. My datastructure is a dict which looks like: results_dict = { LemmaObj1 : [form11, form12, form13, ...], LemmaObj2 : [form21, form22, form33, ...], ... where the LemmaObj are Queryset objects. Generating this dict only takes 0.5 seconds. I force evaluation of the lazy queryset by putting the formij into a list comprehension. views.py lemma_qs = Lemma.objects.prefetch_related('form_set') # ... # some logic goes here # ... for lemma in lemma_qs: form_qs = lemma.form_set.all() form_list = [form.name for form in form_qs if form_filter.search(form.name)] if form_list: results_dict[lemma] = form_list context['results_dict'] = results_dict return render(request, "query.html", context) All this is to say that I'm pretty sure the slowdown isn't coming from database hits. The template in question In my query.html I have two for loops. query.html <div class="lemma-box"> <ol> <li class="lemma-title"> <div class="lemma-col-1"> lemma [{{results_dict|length}}] (group {{group}}) </div> <div class="lemma-col-2"> latin … -
Django makemigrations, 'module' object is not iterable
I'm new to Django and I was trying to use models and migrations, everithing works fine until I try to execute the command: python manage.py makemigrations where it rises the error: TypeError: 'module' object is not iterable I tried to reinstall django and create a new venv and change settings on my code editor, basically everything I could find online, yet I'm stuck with this error (full below). I would appreciate any help, thanks in advanced. Traceback (most recent call last): File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\urls\resolvers.py", line 591, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\checks\urls.py", line 23, in check_reso`enter code here`lver return check_method() File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\urls\resolvers.py", line 409, in check messages.extend(check_resolver(pattern)) File "C:\Users\Emanuele\Desktop\Django_Env\lib\site-packages\django\core\checks\urls.py", line 23, in … -
How to get the selected row's record from a table in django?
I am new to django so I am sorry if this is a noob question. I have created a model "Students" in models.py and a view "Add_Student" for adding a new student, and another view "Display_Students" for displaying all the students. I have a table in which all the students are displaying perfectly with specific columns. But in the table, I added one more column that is "Action" and there is an eye-icon in that column. Now if someone click on that eye-icon so the complete information should be display in a new form/page. Displaying the information in a new form/page isn't the problem, but I don't know how it will work. Similarly, there will be an edit and delete icons. So here, my question comes, when I click on a eye-icon, how the django will get the desired row id from the table? from django.db import models # Create your models here. class students(models.Model): firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) fathername = models.CharField(max_length=50) city = models.CharField(max_length=50) country = models.CharField(max_length=50) state = models.CharField(max_length=50) zip = models.IntegerField(blank=True) address = models.CharField(max_length=100) contact =models.CharField(max_length=20) photo = models.FileField() Views.py from django.shortcuts import render, redirect from home.models import students # Create your views here. def … -
mysqlconnection not working in Django project M1 Mac
im trying just to do python manage.py migrate in my project. python --version Python 3.8.2 My pip list in my venv: Package Version ----------- ------- asgiref 3.3.4 Django 3.2.4 mysqlclient 2.0.3 pip 21.1.3 pytz 2021.1 setuptools 41.2.0 sqlparse 0.4.1 wheel 0.36.2 My Django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'msapi', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', } } I've got an infinite error but most important: Traceback (most recent call last): File "/Users/micenor/Documents/Proyectos/MarvelStudiosAPI/project/.venv/lib/python3.8/site-packages/MySQLdb/init.py", line 18, in from . import _mysql ImportError: dlopen(/Users/micenor/Documents/Proyectos/MarvelStudiosAPI/project/.venv/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/micenor/Documents/Proyectos/MarvelStudiosAPI/project/.venv/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so Expected in: flat namespace in /Users/micenor/Documents/Proyectos/MarvelStudiosAPI/project/.venv/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so version_info, _mysql.version_info, _mysql.file NameError: name '_mysql' is not defined -
what is the false parameter in .delete(False)
I used an example from here which deletes unreferenced files when instance is deleted. one part of the code has this function: """ Only delete the file if no other instances of that model are using it""" def delete_file_if_unused(model,instance,field,instance_file_field): dynamic_field = {} dynamic_field[field.name] = instance_file_field.name other_refs_exist = model.objects.filter(**dynamic_field).exclude(pk=instance.pk).exists() if not other_refs_exist: instance_file_field.delete(False) What does the argument False mean in .delete(False) ? (I couldn't find a reference to it) Thanks -
Templates directory outside Django root
I have a templates directory /var/opt/backoffice/templates and inside there is a template called foo.html. The directory is outside the Django root directory, which is /opt/backoffice. I am trying to get Django to access the foo.html template in /var/opt/backoffice/templates using the get_templates('foo.html') command, but no matter what I try I get the error: django.template.exceptions.TemplateDoesNotExist: foo.html My settings.py for templates is: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'var/opt/backoffice/templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] My question is , how can I configure Django so that I can access the template in /var/opt/backoffice/templates using get_templates('foo.html')? Thank you.