Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when adding AUTH_USER_MODEL to settings.py in DJANGO
i'm getting a "simple" trouble when I try to add AUTH_USER_MODEL constant to settings.py. It returns this error, but when I look to INSTALLED_APPS the app name that I'm still working is there. Here it is: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'PMEapp', ] AUTH_USER_MODEL = "PMEapp.User" This is the error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'PMEapp.User' that has not been installed My installed apps My file system The user model -> It is in models.py These are the things I've tried to solve the problem: 1-Created a User file including all user types in PMEapp folder with user inside didn't work. 2-Moved User file to a folder called User, got the same error. 3-Put all user types in models.py but User(AbstractUser) was still in User.py . Didn't worked too. 4-I've added a User.py file in models folder and imported it to the file that got all the user types. Same error. -
"POST /......... / ......... / HTTP/1.1" 405 0 - Django
I have a problem, in my work I need to insert a system of likes to published posts but by clicking on the button that should give the post a like, nothing happens and this error comes out..."POST /posts/like/ HTTP/ 1.1" 405 0 views.py @ajax_required @require_POST @login_required def post_like(request): post_id = request.POST.get('id') action = request.POST.get('action') if post_id and action: try: post = Post.objects.get(id=post_id) if action == 'like': post.users_likes.add(request.user) else: post.users_likes.remove(request.user) return JsonResponse({'status': 'ok'}) except: pass return JsonResponse({'status': 'error'}) urls.py from django.urls import path, include from . import views app_name = 'posts' urlpatterns = [ path('like/', views.post_like, name='like'), ] index.html {% with total_likes=post.users_likes.count users_likes=post.users_likes.all %} <div class="post-info"> <div> <span class="count"> <span class="total">{{ total_likes }}</span> like{{ total_likes|pluralize }} </span> <a href="#" data-id="{{ post.id }}" data-action="{% if request.user in users_likes %}un{% endif %}like" class="like"> {% if request.user not in users_likes %} Like {% else %} Unlike {% endif %} </a> </div> </div> <div class="post-likes"> {% for user in users_likes %} <div> <p>{{ user.first_name }}</p> </div> {% empty %} <p>No body likes this post yet</p> {% endfor %} </div> {% endwith %} <p>{{ post.id }}</p> <a class="normal-text" href="{{ post.get_absolute_url }}">Discover more...</a> </div> </div> ajax code <script> {% block domready %} $('a.like').click(function(e){ e.preventDefault(); $.post("{% url … -
.distinct() ordering by date not only rows with group by, but group by as well?
Bid.objects.all() gives me two columns with date and bid_value. I want to have only one bid per date. Bid should be the highes value. So Bid.objects.all().order_by("date","bid_value").distinct("date") gives me proper order. But using last not only takes last row from QuerySet, but it takes last element from group_by made from distinct which i dont want. I would want only last element of queryset without any order changes. 1.Bid.objects.all() 2.Bid.objects.all().order_by("date","bid").distinct("date") 3.Bid.objects.all().order_by("date","bid").distinct("date").last() but it should give me 15.11.2022/50zł and actually list(Bid.objects.all().order_by("date","bid").distinct("date").last())[-1] gives me proper object 4.Bid.objects.all().order_by("date","bid").distinct("date").first() How i can still use .last() / .first() - without taking it into list. Because when i use list(Queryset), i have proper values on last objects. But changing queryset to list is not good standard i suppose. -
How to write a Django filter query for multiple values selected from a form without many if statements?
I have several Django forms of which when submitted I store the values like so if the forms are valid with only the min and max price being required, but the other values may be blank or not: max_budget = price_form.cleaned_data['max_price'] #required max_budget = price_form.cleaned_data['max_price'] #required another_value1 = other_form1.cleaned_data['another_value1'] #string another_value2 = other_form1.cleaned_data['another_value2'] #string another_value3 = other_form2.cleaned_data['another_value3'] #string another_value4 = other_form2.cleaned_data['another_value4'] #string another_value5 = other_form3.cleaned_data['another_value5'] #boolen value of 1 if selected another_value6 = other_form3.cleaned_data['another_value6'] #boolen value of 1 if selected I want to query a model (single database table) by using these variable values which correspond to specific fields in that DB as filters. The problem is that currently, I would have to use numerous carefully planned nested if/else statements each containing a variation of the line below to properly filter the DB based on the different possible values or lack thereof. query_results = Model.objects.filter(price__range=(min_budget, max_budget), field_in_the_DB="another_value1", field_in_the_DB="another_value2", field_in_the_DB__icontains="another_value3", field_in_the_DB__icontains="another_value4", field_in_the_DB="another_value5", field_in_the_DB="another_value6").order_by("Another_field_in_the_DB_not_related_these_values") This is because only the min and max prices are required to be entered so something like this would be required. price__range=(min_budget, max_budget) As for the other variables, some may have values or some may be left blank when submitted. Therefore, how can I filter the DB table … -
Code Coverage with Django 4.1 Raising OSError on run
i am using python 3.10.8, django 4.1.4, and coverage 6.5.0. I tried adding the coverage library to my django project to measure the test coverage, I followed the setup process as shown on the Official Django Documentation on testing. Whenever I run the command below, its raises an error. coverage run --source='.' manage.py test myapp myapp name is a dummy name instead of my custom app name Error: OSError: [WinError 127] The specified procedure could not be found Full Traceback is provided here Traceback (most recent call last): File "C:\Users\DUDO\Desktop\projects\salespace inc\app\web\manage.py", line 28, in <module> main() File "C:\Users\DUDO\Desktop\projects\salespace inc\app\web\manage.py", line 24, in main execute_from_command_line(sys.argv) File "C:\Users\DUDO\.virtualenvs\web-15Kcga0E\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\DUDO\.virtualenvs\web-15Kcga0E\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\DUDO\.virtualenvs\web-15Kcga0E\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\DUDO\.virtualenvs\web-15Kcga0E\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\DUDO\.virtualenvs\web-15Kcga0E\lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "C:\Users\DUDO\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\DUDO\.virtualenvs\web-15Kcga0E\lib\site-packages\django\contrib\auth\models.py", line 3, in <module> from … -
Unable to edit an object which has a foreign key in Django
I want to edit an object that has a foreign key in it. The problem that I am facing is that instead of editing the current object it is creating a new one. I think the issue is caused because of foreign key because in models that do not have foreign keys, I am able to edit their objects without any problem. models.py class Room(models.Model): class Meta: ordering = ['room_number'] room_number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], primary_key=True ) ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ('King', 'King'), ('Queen', 'Queen'), ) category = models.CharField(max_length=9, choices=ROOM_CATEGORIES) ROOM_CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=ROOM_CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField() room_manager = models.CharField(max_length=30) class TimeSlot(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() views.py def edit_time_slots(request, pk): if pk: try: time_slot_obj = TimeSlot.objects.get(pk=pk) except Exception: return HttpResponse("Bad request.") else: return HttpResponse("Bad request.") if request.method == 'POST': form = AddTimeSlotForm(request.POST, instance=time_slot_obj) if form.is_valid(): try: Room.objects.get(room_number=time_slot_obj.room.room_number, room_manager=request.user.username) except Exception: return HttpResponse("Bad request.") time_slot = TimeSlot(room=time_slot_obj.room, available_from=request.POST['available_from'], available_till=request.POST['available_till']) time_slot.save() # Implemented Post/Redirect/Get. return redirect(f'../../view_time_slots/{time_slot_obj.room.room_number}/') else: context = { 'form': form, 'username': request.user.username } return render(request, 'add_time_slots.html', context) context = { 'form': AddTimeSlotForm(instance=time_slot_obj), 'username': request.user.username } … -
How can I filter and update my Django model with created_at
I have two models class Records(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Approved = models.BooleanField(default=False) Date = models.DateTimeField(default=datetime.now, blank=True) class Request(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Approved = models.BooleanField(default=False) Date = models.DateTimeField(default=datetime.now, blank=True) I want cron to update Record every 1 minutes if Approved in Request is True I tried this... def deposit(): if Deposit_Request.objects.exists(): check=Deposit_Request.objects.get() with transaction.atomic(): if check.Approved == True: Deposit_Records.objects.filter(user=check.user, Date=check.Date).update(Approved=True) Deposit_Request.objects.get().delete() I dont understand why this logic wont work when this two model object was created at the same time and even when i confirm the datetime, the date, minute and second is the same. -
i was trying to make a virtualenv for python django project ,at that time this error came
ERROR:root:failed to read config file C:\Users\heman\AppData\Local\pypa\virtualenv\virtualenv.ini because FileNotFoundError(2, 'No such file or directory') ERROR:root:AttributeError: 'IniConfig' object has no attribute 'has_virtualenv_section' The system cannot find the path specified. The system cannot find the path specified. The system cannot find the path specified. how to solve this is there any commant for that to fix it using terminal -
How To Dynamically Create Elements in JavaScript
I am struggling to dynamically create tags for each Subheading (h2 element) I have in my blog, and then fill those tags with the text of the Subheading. This is what I have tried so far: <script> const subheadings = document.querySelectorAll("h2"); subheadings.forEach(function(x) { document.getElementById("contents").innerHTML=x; <a href='#' id="contents"></a> }); </script> This resulted in nothing appearing. Any help or advice in which direction to look is greatly appreciated. -
Django database (PostgreSQL) test setup and teardown for user groups not working
In setup I have: new_group, created = Group.objects.get_or_create(name='Sales Manager') SALES_MANAGER = 1 new_group, created = Group.objects.get_or_create(name='Team') TEAM = 2 There a five of these groups. I then use the these variables like this: user.groups.add(TEAM) In the teardown of with: Group.objects.get(name='Team').delete() The first build the test database works fine, but the second produces empty group sets for all my users. I tried not deleting the groups in the teardown, but that made now difference. -
Should I use Node.js or Django for my application?
I'm planing to build a cross-platform app as my first big project. I'm not yet familiar with any of the former frameworks, but I am looking forward to learning them. So far I am familiar with C, C++ and Python. The app will function as following: User uploads a photo, from which text is extracted and stored in associated file (I want to process images on front end, because I can't afford to process everything on the back end) Data is sent to the back end where it is stored With machine learning, data is being analyzed and organized into new groups (in the future I also want to add some AI to find answers to questions posed in the written text on the image) User can access reorganized groups, answers, his profile... So basically I want to do heavy processing on front end; organize everything, enhance data and store profiles/images on back end; implement a smart organization system; be able to access everything again on front end in a package as addictive as Instagram. I know I can easily implement OpenCV and make machine learning algorithms in Python, but I don't know how to make that on front end; … -
Python library to use
I need fill the web application form so which library should I use in Python that help to automate the form filling of website. Python library to used for auto form filling . -
how to reset id whenever a row deleted in django?
i wanted to start id from 1 . whenever a row deleted it skips that number and jump to next number. like in this image it skips number from 1-6 and 8. i want to set it as 1,2,3 this is my models.py class dish(models.Model): id = models.AutoField(primary_key=True) dish_id = models.AutoField dish_name = models.CharField(max_length=255, blank=True, null=True) dish_category = models.CharField(max_length=255, blank=True, null=True) dish_size = models.CharField(max_length=7, blank=True, null=True) dish_price = models.IntegerField(blank=True, null=True) dish_description = models.CharField(max_length=255, blank=True, null=True) # dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True) dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here added images as a foldername to upload to. dish_date = models.DateField() def __str__(self): return self.dish_name this is views.py def delete(request, id): dishs = dish.objects.get(id=id) dishs.delete() return HttpResponseRedirect(reverse('check')) -
Django toggle yes and no
I am having difficulty creating a toggle for Django. This Django is a Chores table listed from the description, category, and is_complete. The is_complete is what I am having trouble with. The toggle should be a href that when you click "yes" it will change to "no" Model.py class ChoresCategory(models.Model): category = models.CharField(max_length=128) def __str__(self): return self.category class Chores(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.CharField(max_length=128) category = models.ForeignKey(TaskCategory, on_delete=models.CASCADE) is_completed = models.BooleanField(default=False) I tried creating a view.py def toggle(request): -
Django channels consumer not receiving data
I'm trying to write a websocket consumer that gets all unread notifications as well as all notifications being created while the client is still connected to the websocket. I'm able to connect to the consumer and it's showing me all active notifications. The problem is that it doesn't show me new notifications when they're being created and sent from the model's save method. consumers.py class NotificationConsumer(WebsocketConsumer): def get_notifications(self, user): new_followers = NotificationSerializer(Notification.objects.filter(content=1), many=True) notifs = { "new_followers": new_followers.data } return { "count": sum(len(notif) for notif in notifs.values()), "notifs": notifs } def connect(self): user = self.scope["user"] if user: self.channel_name = user.username self.room_group_name = 'notification_%s' % self.channel_name notification = self.get_notifications(self.scope["user"]) print("Notification", notification) self.accept() return self.send(text_data=json.dumps(notification)) self.disconnect(401) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) count = text_data_json['count'] notification_type = text_data_json['notification_type'] notification = text_data_json['notification'] print(text_data_json) await self.channel_layer.group_send( self.room_group_name, { "type": "receive", "count": count, "notification_type": notification_type, "notification": notification } ) models.py class Notification(models.Model): content = models.CharField(max_length=200, choices=NOTIFICATION_CHOICES, default=1) additional_info = models.CharField(max_length=100, blank=True) seen = models.BooleanField(default=False) users_notified = models.ManyToManyField("core.User", blank=True) user_signaling = models.ForeignKey("core.User", on_delete=models.CASCADE, related_name="user_signaling") def save(self, *args, **kwargs): if self._state.adding: super(Notification, self).save(*args, **kwargs) else: notif = Notification.objects.filter(seen=False) data = { "type": "receive", "count": len(notif), "notification_type": self.content, … -
instance in Django not working properly unable to get pre populate data
i am trying to populate the fileds in django automatically using the instance but its not working for me so someone help to solve this issue so here is the code def Editquestion(request): askit = askm.objects.get(question = "apple") print(askit) getformdata = editquestf(instance = askit) return render(request, "editquestpage.html", {'edit':getformdata}) -
Django filter queryset
Django framework has a product model with about ten values that need to be filtered (color, type..). I'm trying to create a filter like this: views: ` class FilterCctvView(QuerySetsFromCctv, ListView): paginate_by = 32 def get_queryset(self): queryset = Cam.objects.filter( Q(maker__in = self.request.GET.getlist("maker")) | Q(type_of_cam__in = self.request.GET.getlist("type_of_cam")) ) return queryset in html: <form action="{% url 'filter' %}" method = 'GET'> <ul> <p><strong>Manufacturers</strong></p> {% for cam in view.get_cctv_makers %} <li> <input type="checkbox" class="checked" name="maker" value="{{cam.maker}}"> <span>{{cam.maker}}</span> </li> {% endfor %} </ul> <ul> <p><strong>Type of cameras</strong></p> {% for cam in view.get_cctv_type %} <li> <input type="checkbox" class="checked" name="type_of_cam" value="{{cam.type_of_cam}}"> <span>{{ cam.type_of_cam}}</span> </li> {% endfor %} </ul> <button class="btn btn-success btn-sm" type="submit">Find</button> </form> ` enter image description here But the filter doesn't work correctly! How do I do this correctly? -
Django template: src attribute doesn't work
I've been doing some practice with Django and lately I ran into a problem that I can't solve. I'll give you some context. I have this models (I think you can just focus on the fact that the model has a gitUrl function): class AllTemplates(models.Model): categories = [ ('landing-page', 'landing-page') ] id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) image = models.ImageField(null=True, blank=True) category = models.CharField( max_length=200, choices=categories, default='landing-page') url = models.CharField(max_length=500, null=True) def __str__(self): return self.name @property def templateNumber(self): try: number = self.id except: number = '' return number @property def templateTitle(self): try: title = self.name except: title = '' return title @property def imageURL(self): try: url = self.image.url except: url = '' return url @property def gitUrl(self): try: gitPath = self.url except: gitPath = '' return gitPath The purpose of this model is to keep all the templates I develop in the database. Each template has various fields including 'url', in which I store the github url where the template in question is located. What I can't do is: dynamically make each template have an html file, in which there is an iframe tag whose src attribute points to the github url. Here's what I tried to do. My urls.py … -
Doesn't generate logs file in django
I don't know what to do but nothing works, what could be the problem? LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters':{ 'simple':{ 'format': '[%(asctime)s] %(levelname)s %(message)s', 'datefmt': "%Y.%m.%d %H:%M:%S", }, }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, }, 'handlers': { 'console_prod': { 'class': 'logging.StreamHandler', 'formatter': 'simple', 'filters': ['require_debug_false'], 'level': 'ERROR', }, 'console_debug':{ 'class': 'logging.StreamHandler', 'formatter': 'simple', 'filters': ['require_debug_true'], 'level': 'DEBUG', }, 'file': { 'class': 'logging.FileHandler', 'filename': BASE_DIR / 'logs/forum_api.log', 'level': 'INFO', 'formatter': 'simple', }, }, "loggers" : { "django": { "handlers": ["console_debug", "file"], }, }, } This error is not clear to me File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 572, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'console_debug' -
encode problem when I use NamedTemporaryFile
I want to create a temporary file then send it to the client. The file I send has an encoding problem. I create a temporary file with the function NamedTemporaryFile(). When I put encoding="utf-8" to NamedTemporaryFile, I get this error: ** PermissionError: [WinError 32] The process cannot access the file because this file is in use by another process: 'C:\\..\\AppData\\Local\\Temp\\tmpglkdf_2o' ( When i don't write encoding="utf-8", all goes well, I can download the file but with encoding problem ) views.py from django.http.response import HttpResponse from django.http import StreamingHttpResponse from wsgiref.util import FileWrapper import mimetypes import pandas as pd import pdb; def page(request): object = pd.DataFrame(data={"ColumnWithé": ["éà"]}) fileErr(request, object=object) def fileErr(request, object=None): # Create a temp file if(isinstance(object, pd.DataFrame)): print("========== IF ==========") #pdb.set_trace() f = NamedTemporaryFile(delete=False, encoding="utf-8") object.to_csv(f, sep=',') request.session["errpath"] = f.name.replace("\\","/") # Send the temp file when the user click on button else: print("========== ELSE ==========") #pdb.set_trace() filename="err.csv" file_path = request.session.get("errpath") response = StreamingHttpResponse(FileWrapper(open(file_path, 'rb')), content_type=mimetypes.guess_type(file_path)[0]) response['Content-Length'] = os.path.getsize(file_path) response['Content-Disposition'] = "Attachment;filename=%s" % filename return response .html <a href="{% url 'downloadfile' %}"> urls.py urlpatterns = [path("download-file", views.fileErr, name="downloadfile"),] The result when i don't write encoding="utf-8" -
WHY AM I GETTING SUBPROCESS ERROR WHEN I TRY TO INSTALL CERTAIN DJANGO PACKAGES IN CPANEL?
I am trying to host my django application on cpanel. I have moved the project into the file manager and done all configurations. Now, I need to run some pip installs in the cpanel terminal and thats where the problem is. Whenever I try to do pip install django-allauth, I get a subprocess error and I dont know why. Django-allauth is not the only package that gives me this kind of error. psycopg2-binary does as well. SOLUTIONS THAT I HAVE ALREADY TRIED: i have upgraded pip, wheel and setup tools. I have changed the python versions being used for my project. I have changed the django versions as wel. yet, the problem persists. Please I really need help. -
Django Field 'id' expected a number but got 'autobiography'
I am working on a project that allows me to upload books to database and sort them by them their collection. The problem is that whenever i upload and try to filter out books from a particular collection i get the error Field 'id' expected a number but got 'autobiography' models.py class BookDetails(models.Model): collections = models.CharField(max_length=255, choices=COLLECTION, default="") class Meta: verbose_name_plural = "BookDetails" def __str__(self): return self.collections class Books(models.Model): """ This is for models.py """ book_title = models.CharField(max_length=255, default="", primary_key=True) book = models.FileField(default="", upload_to="books", validators=[validate_book_extension], verbose_name="books") collection = models.ForeignKey(BookDetails, on_delete=models.CASCADE, default="") class Meta: verbose_name_plural = "Books" def __str__(self): return self.book_title forms.py class BookInfo(forms.ModelForm): class Meta: model = BookDetails fields = ["collections",] class BookFile(BookInfo): book = forms.FileField(widget = forms.ClearableFileInput(attrs={"multiple":True})) class Meta(BookInfo.Meta): fields = BookInfo.Meta.fields + ["book",] views.py def books(request): if request.method == "POST": form = BookFile(request.POST, request.FILES) files = request.FILES.getlist("book") try: if form.is_valid(): collection = form.save(commit=False) collection.save() if files: for f in files: names = str(f) name = names.strip(".pdf") Books.objects.create(collection=collection, book_title=name, book=f) return redirect(index) except IntegrityError: messages.error(request, "value exist in database") return redirect(books) else: form = BookFile() return render(request, "books.html", {"form":form}) def test(request): data = Books.objects.filter(collection="autobiography") template = loader.get_template('test.html') context = {"data":data} return HttpResponse(template.render(context, request)) so basically what i am trying … -
Django Model Data Only To XML
I have this simple model class TestData(models.Model): rcrd_pk = models.AutoField(primary_key=True) Name = models.CharField(max_length=50) desc = models.CharField(max_length=300, blank=True, null=True) I want to get XML of model data. so I have written this code from sms_api.models import TestData from django.core import serializers data = TestData.objects.all() XmlData = serializers.serialize("xml",data) print (XmlData) This code Export XML like this: <?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"> <object model="sms_api.testdata" pk="1"> <field name="Name" type="CharField">Roqaiah</field> <field name="desc" type="CharField">Rogaiah is Old Arabic Name</field> </object> <object model="sms_api.testdata" pk="2"> <field name="Name" type="CharField">Khadeejah</field> <field name="desc" type="CharField">Kahdejah is an Arabic Name</field> </object> </django-objects> This way exported the Model with datatypes and others unwanted deteails. I want the ouput to be simple like so <?xml version="1.0" encoding="utf-8"?> <django-objects"> <object> <Name>Roqaiah</Name> <desc>Rogaiah is Old Arabic Name</desc> </object> <object> <Name>Khadeejah</Name> <desc>Kahdejah is an Arabic Name</desc> </object> </django-objects> The last Thing if I can change the tags of the xml, so those tags <django-objects> <object> can be <RowSets> <Row> -
How to give a post (in a forum) a tag (django-taggit) with checkboxes?
In my Web Forum I have an add Post Page it looks like this: How can I get all clicked tags as a django-taggit object or whatever then send them to my backend and save them in the database? My views.py looks like that: def post_question_tags(request): current_user = request.user if request.method == "POST": Post.objects.create(title = request.POST["title"], description = request.POST["description"], tags = request.POST["tags"], author = current_user) all_tags = Tag.objects.all() return render(request, "post_question_tags.html", {'all_tags' : all_tags, 'current_user': current_user}) My Template <div class="tags"> {% for tag in all_tags %} <div class="tag"> <p class="tag-title">{{ tag.name }}</p> <input type="checkbox" class="checkbox-button" name="checkboxes" value="{{ tag.name }}" /> <p class="description">{{ tag.description }}</p> </div> {% endfor %} </div> -
class "is not defined" in django models that rely on eachother
I have two classes in my models.py. If I change the order I define the classes it makes no difference and at least one of them give an error about something not being defined. class Item(models.Model): offers = models.ManyToManyField(Bid) class Bid(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE)