Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pass a value to a pop-up window Django
I have some some description and want get its in my pop-up window. Then I click on div with type button I must get value in pop-up <div class="content-wrapper bg-white"> <!-- container --> <div class="container-fluid"> <div class="page-body inner-page"> <div class="row"> <div class="col-xs-12 col-sm-6"> <div class="inner-page-header"> <div class="col-xs-12 col-sm-4 col-lg-3" style="margin-bottom: 25px; mso-hide: all"> {% if text.description %} <div class="col-xs-12" type="button" data-toggle="modal" data- target="#exampleModal" > {{ text.description }} </div> {% endif %} </div> </div> </div> </div> </div> </div> </div> this component of code from where I must to get {{ text.description }} But my modal window is in base.html and I don't know how must bubble {{ text.description }} which change dynamical (I want- then I click on some of them - in modal window get {{ text.description }} exactly it's. <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-scrollable" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% if text.description %} {{ text.description }} {% endif %}} </div> <div class="modal-footer"> <button type="button" data-dismiss="modal" >Close</button> </div> </div> </div> </div> Please help me -
specific attribute from an object will be randomly show on template
I have tried to show an specific attribute values randomly. Just dictionaries are appeared in my web page which I have showed. I want to show the actual questions which are stored in my Question model class Exam(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,related_name='exam_user') subject=models.ForeignKey(Subject,on_delete=models.CASCADE,related_name='exam_subject',default=True) choices={ (1,'QUIZ'), (2,'MIDTERM'), (3,'FINAL') } exam_type=models.IntegerField(choices=choices) exam_mark=models.IntegerField() question=models.ManyToManyField(Question,related_name='exam_question') exam_date=models.DateTimeField(auto_now_add=True) class Meta: ordering=('-exam_date',) def __str__(self): return 'Exam-type'+'-'+str(self.exam_type) `````````````````````````````````````````````````````````````````````````````` class Question(models.Model): subject = models.OneToOneField(Subject,on_delete=models.CASCADE, related_name='question_subject') question_title=models.CharField(max_length=5000,unique=True) option_first=models.CharField(max_length=100,default='') option_second=models.CharField(max_length=100,default='') option_third= models.CharField(max_length=100,default='') option_fourth= models.CharField(max_length=100,default='') mark=models.IntegerField() def __str__(self): return (self.question_title)+'--1--'+str(self.option_first)+'--2--'+str(self.option_second)+'--3--'+str(self.option_third)+'--4--'+str(self.option_fourth) this is my view where I have create a query and passing this to my template def showExam(request,id): exam_list = Exam.objects.filter(id=id) questionlist=Exam.objects.filter(id=id).order_by('?').values('question').distinct() dict={'exam':exam_list,'questionlist':questionlist} return render(request,'question_app/showExam.html',context=dict) <table class="table table-bordered table-striped "> <tr> <th>Exam Type</th> <th>User Id</th> <th>Question List</th> <th>Exam Mark</th> <th>Exam Date</th> </tr> {% for row in exam %} <tr> <td>{{ row.exam_type }}</td> <td>{{ row.id }}</td> <td> {% for qes in questionlist %} <ol>{{ qes }}</ol> {% endfor %} </td> <td>{{ row.exam_mark }}</td> <td>{{ row.exam_date }}</td> </tr> {% endfor %} </table> In the image there are some questions which are randomly appeared but the real questions in this dictionaries cant be fetched from it -
Exclude child in nested serializer
I have three serializers: class BookingSerializer(serializers.ModelSerializer): owner = serializers.CharField(source="owner.username", read_only=True) class Meta: model = Booking fields = ( "id", "createdDate", "comments", "location", "date", "operator", "status", "owner", ) class CompanySerializer(serializers.ModelSerializer): bookings = BookingSerializer(many=True, read_only=True) owner = serializers.CharField(source="owner.username", read_only=True) class Meta: model = Company fields = ("id", "name", "description", "location", "bookings", "owner") class UserSerializer(serializers.HyperlinkedModelSerializer): bookings = BookingSerializer(many=True, read_only=True) companies = CompanySerializer(many=True, read_only=True) class Meta: model = User fields = ("url", "id", "username", "email", "bookings", "companies") UserSerializer return the all the fields, but the bookingserializer is called twice. { "url": "http://localhost:8000/users/4/", "id": 4, "username": "test", "email": "test@test.com", "bookings": [ { ... } ], "companies": [ { ... "bookings": [ { ... } ] } ] } How do I exclude the bookings field in companies when using UserSerializer? I would still like to have CompanySerializer return bookins in other cases. Thanks! -
Django REST Frameworking overfetching when using PrimaryKeyRelatedField
My Django model: class Quest(models.Model): name = models.CharField(max_length=255) is_completed = models.BooleanField(default=False) characters = models.ManyToManyField(Character, blank=True) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, editable=False) The DRF serializer: class QuestSerializer(serializers.ModelSerializer): characters = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Quest fields = "__all__" The problem that I am having is that when I am fetching the list of quests, that it executes a query like this: SELECT ("quests_quest_characters"."quest_id") AS "_prefetch_related_val_quest_id", "characters_character"."id", "characters_character"."legacy_id", "characters_character"."name", "characters_character"."subtitle", "characters_character"."avatar", "characters_character"."avatar_crop", "characters_character"."text", "characters_character"."is_npc", "characters_character"."is_hidden", "characters_character"."dm_notes", "characters_character"."campaign_id", "characters_character"."created_at", "characters_character"."updated_at" FROM "characters_character" INNER JOIN "quests_quest_characters" ON ("characters_character"."id" = "quests_quest_characters"."character_id") WHERE "quests_quest_characters"."quest_id" IN (1281, 1280, 1279, 1278, 1277, 1276, 1275, 1274, 1273, 1272, 1271, 1270, 1269, 1268, 1267, 1266, 1265, 1264, 1263, 1262, 1261, 1260, 1259, 1258, 1257, 1256, 1255, 1254) That is a big query with a lot of fields, even though only an array of character ids is given back in the JSON result, so why is it fetching all this information? It should just fetch this, I would imagine: SELECT "character_id" FROM "quests_quest_characters" WHERE "quest_id" IN (1281, 1280, 1279, 1278, 1277, 1276, 1275, 1274, 1273, 1272, 1271, 1270, 1269, 1268, 1267, 1266, 1265, 1264, 1263, 1262, 1261, 1260, 1259, 1258, 1257, 1256, 1255, 1254) My view: class QuestController(viewsets.ModelViewSet): serializer_class = QuestSerializer … -
Django Backend Image not displaying
I've tried many ways but nothing works. I can't find a solution to this issue. My frontend is React and My backend is Django. On browser only show the URL path link of the image instead of an image. I've tried to add this code to another template and It was working but this one does not work. browser display My settings.py INSTALLED_APPS = ['django.contrib.staticfiles',] STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' My urls.py from django.views.generic import TemplateView from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if not settings.DEBUG: urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] My Model looks like this class Product(models.Model): name = models.CharField(max_length=200) image = models.ImageField(blank=True) description = models.TextField() price = models.DecimalField(max_digits=9, decimal_places=2) createdAt = models.DateTimeField(auto_now_add=True) def __str__(self): return f" '{self.name}' " -
Confirmation message after deletion Django
How can I display a success message on a different page after I have deleted someone? The page it redirects to is a page that displays all of the workers. I've also tried displaying it in the current page using timer.sleep(10) to stop the redirect for a while but it seems to ignore that code and instantly redirect the page. Either way is fine with me. I'm using the DeleteView generic display view. views.py class WorkerDelete(SuccessMessageMixin, LoginRequiredMixin, DeleteView): model = Worker context_object_name = 'worker' success_url = reverse_lazy('workers') worker_confirm_delete.html (Template) {% block content %} <a href="{% url 'workers' %}">Go Back</a> <form method="POST"> {% csrf_token %} <p>Are you sure you want to delete this worker? "{{worker}}"</p> <input type="submit" value="Delete"> </form> {% endblock content %} -
can't iterate over multiple zip lists in django template
I'm trying to iterate a zip variable to templates. So I work well with two items but after adding 3 items to zip variable I can't iterate it in for loop like before.Here 'subj' lastest item. zip variable zipped_lists = zip(card_postings, arrays, subj) template {% for card,posts,contents in zipped_lists %} <div class="card"> <div class="card-body"> <h4 class="text-center">{{ card }}</h4> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"> {% for post in posts%} <div class="col"> <div class="card"> <div class="card-header text-center text-primary"> <h5>{{ post }}</h5> </div> <ul class="list-group list-group-flush"> {% for par,gray,aux,verb in contents %} <li class="list-group-item border-0"> <i>{{par}} {{gray.0}} {{aux.0}} {{verb.0}}</i> </li> {% endfor %} </ul> </div> </div> {% endfor %} </div> </div> </div> {% endfor %} By the way I print 'suj' to terminal it also works well. -
Django - Count and filter in queryset
i want to create a complex queryset , after many time witout sucess :( i ask your help, is my models: class Commit(odels.Model): date = models.DateTimeField(auto_now_add=True) created = models.BooleanField(default=False) creator = models.ForeignKey( get_user_model(), on_delete=models.SET_NULL, null=True, blank=True, related_name="%(class)s_creator" ) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') uuid = models.CharField(max_length=200) updated_fields = models.TextField(null=True, blank=True) i want to count how many "commit" user have, remove user if user as no "commit" and commit lower than 7 days , sort by upper, and remove my account to this filter , how can to this ? thx -
How to relay user actions from the server to an external device
I have a web interface that allows the user to send remote commands to 1 or 2 robots. Currently the tasks are saved in the database (for logging as well) and the robot(s) keeps polling the django backend using GET requests every 125ms which gives acceptable response time without overly stressing the backend. In short: Action(User) -> [Remote Control UI] -> Django -> DB (based on user input) To get the actions the robot then does a GET request to Django as something like: while(ros::ok()) { response = requests.get(task_url, timeout=5) // input task(s) to state machine // execute task if possible rate.sleep(); } My question is: is there a better way? The remote control is sometimes disabled as the robot goes out of Wi-Fi so the solution needs some degree of flexibility to re-connection, IP changes and connection errors. I though about possible alternatives but not sure they are feasible: Require robots to register and save their IP (?) and send the command to the robot if registered Multicast the command to the entire Wi-Fi subnet (?) and let the robot read it Use django channels or some similar technology? I only found examples with [django or flask] + javascript. … -
Django: ValueError: Cannot assign "<User: x>": "UserRelatinoship.x" must be a "User" instance
I am trying to automatically create a relationship between two test users in a migration in Django. My migration code looks like this: # Generated manually from django.db import migrations, transaction from django.contrib.auth import get_user_model def setup_test(apps, schema_editor): User = get_user_model() User.objects.create_superuser("admin", "admin@gm.org", "123") x = User.objects.create_user( username="x", email="a@gm.org", password="123" ) y = User.objects.create_user( username="y", email="b@gm.org", password="123" ) UserRelatinoship = apps.get_model("myapp", "UserRelatinoship") UserRelatinoship.objects.create(x=x, y=y, active=True) class Migration(migrations.Migration): dependencies = [ ("myapp", "0001_initial"), ("myapp", "0002_manual"), ] operations = [ migrations.RunPython(setup_test), ] The users are created fine, but then when I try to create the relationship I get the error ValueError: Cannot assign "<User: x>": "UserRelatinoship.x" must be a "User" instance.. Note I modified some names from my original code. Any help is greatly appreciated! -
can't bind ForeignKey for form_valid
I am making hotel reservations but I have a problem with class OrderCreateView (generic.CreateView): I want to be linked to the hotel how can you make sure that there is a link to the hotels? My code: I think everything is fine here #models.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ) order = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name='order' ) create_at = models.DateTimeField( auto_now_add=True ) arrival_date = models.DateTimeField( verbose_name='Дата заезда:' ) departure_date = models.DateTimeField( verbose_name='Дата отъезда:', ) name = models.CharField( max_length=50, verbose_name='Имя:' ) surname = models.CharField( max_length=50, verbose_name='Фамилия:' ) fatherland = models.CharField( max_length = 50, verbose_name='Отечество:', ) id_card = models.CharField( max_length = 50, verbose_name='Паспорт:', ) def __str__(self): return f"{self.name}" class Meta: verbose_name = 'Брони' verbose_name_plural = 'Брони' ordering = ('-create_at', ) but I think there is a problem in the form_valid, help me solve it please #views.py class OrderCreateView(generic.CreateView): model = Order form_class = OrderForm success_url = reverse_lazy('success_message') template_name = 'order/create.html' def form_valid(self, form): form.instance.user = self.request.user self.order = get_object_or_404(Hotel, kwargs={"pk": self.object.pk}) form.instance.order = self.order return super(OrderCreateView, self).form_valid(form) def successmessage(request): return render(request, 'order/success.html') Help me please -
Google Cloud - Django - OSError: [Errno 30] Read-only file system
I have deployed my django project on google cloud. One module of my app involves uploading files. When I am uploading my files on local server the files are successfully uploading but when I am trying to upload the files from the production server it is giving me the following error: OSError at /uploadrecords [Errno 30] Read-only file system: '/workspace/media/test.pdf' Following is my code for uploading files and the settings: #views.py image = request.FILES['filerecord'] fs = FileSystemStorage() filename = fs.save(image.name, image) obj.upfile = fs.url(filename) obj.save() #setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #MEDIA_ROOT = BASE_DIR / "media" Kindly suggest me a solution -
Django ORM create rows dynamically with _meta.get_fields()
I am writing a function to read xlsx and write this data to the database with Django. But I have so many fields that I cannot define statically. I want to write these fields to the database with a certain algorithm. When designing this, I get the class attributes with _meta.get_fields(). But as seen in this example, attributes always remain None. In views.py there is an example between BEGIN and END codes. How can i solve this problem? views.py # ... some codes ... @login_required(login_url='/admin/login/') def import_process(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file_in_memory = request.FILES['file'].read() wb = load_workbook(filename=BytesIO(file_in_memory), data_only=True) ws = wb.worksheets[0] ws_company_name = str(ws["D9"].value) ws_company_address = str(ws["D10"].value) # ... some codes ... # Company Tower Get ID loop company_staff = CompanyStaff.objects.filter(company_id=Company.objects.filter(company_name=ws_company_name)[0].id)[0] for col in COLUMN_PARAMETER_LIST: column_cell = str(col) + str(COLUMN_PARAMETER_BEGIN) ws_tower_type = str(ws[column_cell].value) tower_type = TowerType.objects.filter(tower_type=ws_tower_type)[0] c_tower_object = CompanyTower.objects.filter(company_staff_id=company_staff,tower_type_id=tower_type)[0] tower_data = TowerData.objects.create(company_tower_id=c_tower_object) ROW_IDX = int(ROW_PARAMETER_BEGIN-1) # ****************** BEGIN ****************** # site_fields = tower_data._meta.get_fields() site_fields_names = [f.name for f in site_fields][1:] for mfield in site_fields_names: if any(word in str(mfield) for word in TOWER_DATA_EXCLUDE_FIELDS_NEW): continue else: ROW_IDX += 1 tower_data_cell = str(col)+str(ROW_IDX) tower_data_cell_value = ws[tower_data_cell].value tower_data.mfield = tower_data_cell_value if str(mfield) == 'ph': # Example Field print(tower_data.mfield) … -
['“<BoundField value=14.99 errors=None>” value must be a decimal number.']
I am creating a restaurant model and I get an error ValidationError at /api/restaurateur/create_meal/ ['“<BoundField value=14.99 errors=None>” value must be a decimal number.'] How can I fix this error? My view: @action(['POST'], detail=False, url_path='create_meal') def create_meal(self, *args, **kwargs): meal_data = self.request.data restaurant = Restaurant.objects.get(owner=self.request.user) serializer = MealSerializer(meal_data) meal_create(title=serializer["title"], description=serializer["description"], price=serializer["price"], restaurant=restaurant, slug=serializer["slug"], discount=serializer["discount"], ) serivce.py def meal_create(title, description, price, restaurant, slug, discount): meal = Meal.objects.create(title=title, description=description, price=price, restaurant=restaurant, slug=slug, discount=discount, ) meal.save() models.py class Meal(models.Model): """Meal""" title = models.CharField(max_length=255) description = models.TextField(default='The description will be later') price = models.DecimalField(max_digits=9, decimal_places=2) discount = models.IntegerField(default=0) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) slug = models.SlugField(unique=True) Why am I getting this error and how can I fix it? -
Using __range in datetime in Django
I bumped into some problem . I have this in views.py orders_completed = Order.objects.filter(customer=customer, complete=True) orders= [] for i in orders_completed : ordered_date = i.date_ordered valid_date = ordered_date + timedelta(days=5) if Order.objects.filter(id=i.id , date_ordered__range=(ordered_date ,valid_date)): orders.append(i) And I have sent orders in context for frontend. After this , even if the order places was on september 19th , its still showing when today is 28 th of September. I have specified the valid date as +5 of ordered date. -
How can I use a custom search field (model property) to search in Django Admin?
This is very similar to this question, but unfortunately, I still couldn't get it working. I have a model, with a property that combines a few fields: class Specimen(models.Model): lab_number = ... patient_name = ... specimen_type = ... @property def specimen_name(self): return f"{self.lab_number}_{self.patient_name}_{self.specimen_type}" In Django Admin, when someone does a search, I can use the search_fields attribute in the Model Admin to specify real fields, but not the specimen_name custom field: def specimen_name(inst): return inst.specimen_name specimen_name.short_description = "Specimen Name" class SpecimenModelAdmin(admin.ModelAdmin): list_display = ('specimen_name', 'patient_name', 'lab_number', 'specimen_type') search_fields = ('patient_name', 'lab_number', 'specimen_type') Doing a search using the code above, it will search the individual fields, but if I try to search for a full specimen_name in Django Admin, it won't find it, because none of the fields contain the exact, full specimen name. The SO question I linked to above pointed me in the right direction - using get_search_results. My code now looks something like this: class SpecimenModelAdmin(admin.ModelAdmin): ... search_fields = ('patient_name', 'lab_number', 'specimen_type') def get_search_results(self, request, queryset, search_term): if not search_term: return queryset, False queryset, may_have_duplicates = super().get_search_results( request, queryset, search_term, ) search_term_list = search_term.split(' ') specimen_names = [q.specimen_name for q in queryset.all()] results = [] for term in … -
how to fetch a item from model and save the same item in another model with form django
i have an ecommerce site i have tow model one name is item and other add to cart i want to fetch the model with it it id and want to the same item in another model so how i can do that this what i tried class Item(models.Model): auth = [ ('✔','✔'), ('✖','✖') ] categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='our_items') subcategories = models.ForeignKey(Subcategories, on_delete=models.CASCADE, related_name='products') name = models.CharField(max_length=200, blank=False) contain_size = models.CharField(max_length=50, blank=True) brand_name = models.CharField(max_length=100, blank=False, default=None) swag = models.BooleanField(default=False) footwear = models.BooleanField(default=False) first = models.ImageField(upload_to='items', blank=False) second = models.ImageField(upload_to='items', blank=False) taken_from = models.CharField(max_length=1000) color = models.CharField(max_length=30, blank=True) material = models.CharField(max_length=50, blank=False) return_policy = models.CharField(max_length=100, blank=False, default='7Days Return Policy') stock = models.CharField(max_length=50, blank=False, default='In Stock') authentic = models.CharField(max_length=1,blank=False,choices=auth, default='✔') price = models.FloatField(blank=False,) actual_price = models.FloatField(blank=False) type = models.CharField(blank=True, max_length=100,) about = models.CharField(blank=True,max_length=100,) offer = models.CharField(max_length=4, blank=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) description = models.TextField(blank=True) @staticmethod def get_items_by_id(ids): return Item.objects.filter(id__in = ids) def __str__(self): return self.name second model class Addtocart(models.Model): User = models.OneToOneField(User, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='cart_item') added_date = models.DateField(auto_now=True) def __str__(self): return self.user.username know what i want is to take that item id from item model and save it in add to cart model for that … -
wagtail: Adding page as the first child of the parent page on creation
Im trying to add the created list page as the first child of the parent Index page. The problem is that when I use django treebeard api django treebeard api it succeeds sometimes but other times it shows me an error: {'path': ['Page with this Path already exists.']} How can I solve this? CODE: @receiver(post_save, sender=ListPage) def move_page(sender, instance, **kwargs): instance.move(instance.get_parent(), pos='first-child') -
Get Average of three Boolean Fields
I am building a Simple Blog App and I am trying to get the average of three Boolean fields. For Example :- There are three boolean fields in model named bool_1, bool_2 and bool_3 and two of any three is True then show something. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) bool_1 = models.BooleanField(default=False) bool_2 = models.BooleanField(default=False) bool_3 = models.BooleanField(default=False) views.py def page(request): queryset = BlogPost.object.filter(user=request.user)..aggregate( avr=Avg(F('bool_1') + F( 'bool_2 ') + F('bool_3 '))).order_by('avr') context = {'queryset':queryset} return render(request, 'page.html', context) But it shows operator does not exist: character varying + character varying LINE 1: SELECT AVG((("app__blogpost"."bool_1" + "app__blogpost.. What have i tried :- I also tried by Case and then method like :- queryset = BlogPost.objects.filter( user=request.user).aggregate( boolean_value=Count(Case(When(bool_1=True, then=Value("Working"))))) but it showed {'boolean_value': 0} I have tried many times but it is still not working. Any help would be much Appreciated. Thank You. -
Django, storing PDF documents as archive belongs to objects
I have question about the django. I have many applications on my project, but i am trying to create different two app, and first one has PDF documents section. On the other hand i am trying to use other application as archive of this PDF's of the created objects. How can i do that, i could not imagine that how it will be coded. Thanks in advance. All notion are valuable! -
Django Postgres Connection Reset in Docker
I have a Django app and Postgres DB running on two separate containers. The DB connection from Django continues to be set whenever I startup the containers. I tried restarting Django, but get the same result. I'm able to go into psql from the Django container and view the tables. Error traceback (most recent call last): File "/usr/local/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/local/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/channels/management/commands/runserver.py", line 76, in inner_run self.check_migrations() File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 235, in _cursor self.ensure_connection() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in … -
How to assign an event by passing the primary key (id) list as a parameter using javascript
I am outputting student information to table in django. The function we want to create is that the currently logged in teacher selects the checkbox of the desired student and clicks the "Add Teacher" button, then the name of the currently logged in teacher is added to the clicked student's teacher field. The name of the currently logged in teacher can be obtained as {{ request.user.name }}. <table class="maintable"> <thead> <tr> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Name</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Age</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Register Date</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Teacher</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Select</th> </tr> </thead> <tbody> {% for student in students %} <tr student-id="{{ student.id }}"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.register_date }}</td> <td>{{ student.techer }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <input type="button" value="Add Teacher" class="addteacher"> The method I thought of is as follows, but the code does not work and seems to need improvement. Help! urls.py path('student/<int:id>/edit/', views.edit_student, name='edit_student') --> It looks like the parameter needs a list. views.py def edit_student(request, id): student = get_object_or_404(Student, pk=id) --> Just like the parameter in urls.py needs to be changed to a list … -
In Django E-commerce app, how I send user wishlist (when user is not logged in) data to cart after user logged in, I used session for Wishlist
For that I used session to store product information for the wishlist and bu can't send when user is logged in/. -
Django backward foreign key query not working
hi i am working on a chat application on django with django channels and i am trying to query all the first messages of the user here when i do user.message_set.all() it is throwing AttributeError at / 'User' object has no attribute 'message_set' full traceback: Traceback (most recent call last): File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/__neeraj__/Documents/chat/home/views.py", line 10, in index print(i.messages_set.all()) AttributeError: 'User' object has no attribute 'message_set' my models.py class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey( User, on_delete=models.CASCADE, related_name="receiver" ) text = models.CharField(max_length=2000) created_on = models.DateTimeField(auto_now=True) my view : def index(request): users = User.objects.all() context = {"users": users} for user in users: print(user.message_set.all()) return render(request, "index.html", context=context) is this because i have double foreign key reference of user model on message table? -
while going through api/register url the following error occurs AttributeError: 'function' object has no attribute '_meta'
urls.py file from .views import RegisterAPI , LoginAPI from knox import views as knox_views from django.urls import path from accounts import views urlpatterns = [ path('' , views.index , name='home') , path('register' , views.register , name='register') , path('login' , views.login , name='login') , path('logouts' , views.logouts , name='logouts') , path('api/register/', RegisterAPI.as_view(), name='register'), path('api/login/', LoginAPI.as_view(), name='login'), path('api/logout/', knox_views.LogoutView.as_view(), name='logout'), path('api/logoutall/', knox_views.LogoutAllView.as_view(), name='logoutall'), ] above file is my urls.py file in which i am getting error when i am trying api/register