Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can I get the name of admin who updated the record in django?
I am new to Django and I am trying to make an application and I am stuck with this. I would like to get the name of the admin who updated the record and add save it. is that possible. Please help. Thanks in advance. -
Render radio values using Django BoundField
Hi I want to return form radio values as a JSON from my view. I don't want the html tags, just raw data of radio values. This is my views.py code: def FormBotAPI(request): form = UserForm(request.POST or None) if request.method == 'POST': if form.is_valid(): instance = form.save() context = { 'form': form } for x in form.fields: data = { 'label_str': form[x].label, 'values': str(form[x]), } return JsonResponse(data, safe=False) forms.py: class UserForm(ModelForm): class Meta: model = User fields = '__all__' -
Using related models with conditional expression
Goal: use a related model attribute as a filter inside a conditional expression for an annotation. I'm currently adding some functionality to an old Django app, this app has some design issues and i have nothing to do with it. After some research I found conditional expressions, this is great and what I needed. However I'm not being able to make it. Let's have model A, model B and model C. class ModelA(models.Model): name=models.Charfield() reference=models.ForeignKey('app.ModelB') class ModelB(models.Model): name=models.Charfield() class ModelC(models.Model): name=models.Charfield() reference=models.ForeignKey('app.ModelB', related_name='some_reference') bool_field=models.BooleanField() And this is what I would like to do: ModelA.objects.all().annotate(some_field=When(Q(reference__some_reference__bool_field=True), then=F('reference_some_reference_name'))) This should work since it is being interpreted by python, but I get some Syntax Error from MySQL. What am i doing wrong? Is this even possible? This is what I'm getting: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHEN `ParametrosPreciosProveedor`.`already_iva` = 1 THEN `ParametrosPreciosProve' at line 1") 'ParametrosPreciosProveedor' is ModelC in this example and 'already_iva' is bool_field. -
Django upload FileField and ImageField in differnt servers
I want to make a system where user can upload document files and also images (both for different tasks) and i want to store the files in my own ftp server and images in s3 bucket. never saw a django approach like this, where FileField and ImageFields can be uploaded to different servers for example, let's say when user uploads a file the file gets uploaded to my ftp server FTP_USER = 'testuser'#os.environ['FTP_USER'] FTP_PASS = 'testpassword'#os.environ['FTP_PASS'] FTP_PORT = '21'#os.environ['FTP_PORT'] DEFAULT_FILE_STORAGE = 'storages.backends.ftp.FTPStorage' FTP_STORAGE_LOCATION = 'ftp://' + FTP_USER + ':' + FTP_PASS + '@192.168.0.200:' + FTP_PORT # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static_my_proj"), ] STATIC_ROOT = os.path.join(BASE_DIR, "static_cdn", "static_root") MEDIA_URL = 'ftp://192.168.0.200/' MEDIA_ROOT = 'ftp://192.168.0.200/'#os.path.join(BASE_DIR, "static_cdn", "media_root") but problem is images now goto ftp server also because of this DEFAULT_FILE_STORAGE = 'storages.backends.ftp.FTPStorage' yeah i know i can make different directories inside uploaded server root directory like this def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filename): # print(instance) #print(filename) new_filename = random.randint(1,3910209312) name, ext = get_filename_ext(filename) final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext) return "myapp/{new_filename}/{final_filename}".format( new_filename=new_filename, final_filename=final_filename ) class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) document = … -
Django URL template prepending last url in urls.py erroneously
As the title states, the {% url 'urlName' %} is evaluating to a url that includes extra information prepended. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('logout', include('dashboard.urls')), path('signout/<int:id>/<int:payment>/', include('dashboard.urls')), path('shifts-in-range', include('dashboard.urls')), path('charts', include('dashboard.urls')), ] and in the appname/urls.py we have a very similar view: urlpatterns = [ path('', auth_views.LoginView.as_view(template_name='index.html'), name='login'), path('signout/<int:id>/<int:payment>/',signout, name='signout'), path('shifts-in-range',shiftsInRange,name='shifts-in-range'), path('charts', charts, name='charts'), ] When using this statement: var signoutURL = "{% url 'signout' 0 2 %}"; it evaluates to the url chartssignout/0/2/ for some reason the last path in urls.py urlpatterns is being prepended to the evaluated url. switching the order of the urlpatterns makes it evaluate with the new last pattern as well. What is the cause of this and how can I prevent it from happening? it is also worth noting that when I hardcode the url signout/0/2/, it does not function correctly and redirects to the root "/". -
Reduce the headache on database when using ModelChoiceField
please I need your help how to reduce the database call when using ModelChoiceField a it requires queryset and I have to use it three times separately with a model that is recursively foreign key on itself, the code is below: ModelForm code in the init function self.fields['category'] = forms.ModelChoiceField(queryset=queryset) self.fields['sub_category'] = forms.ModelChoiceField(queryset=) self.fields['product_type'] = forms.ModelChoiceField(queryset=) the model class: class Category(ProjectBaseModel, AuditLogMixin): parent_id = models.ForeignKey('self', related_name='children', blank=True, null=True, on_delete=models.CASCADE,verbose_name=_('Parent')) what i tried to do is collect all ids of the desired categories in array and make only one filter queryset with them like the following: category = auction.category sub_category = category.parent_id product_type = sub_category.parent_id ids= [category.id,sub_category.id,product_type.id] queryset = Category.objects.filter(id__in=ids) but to proceed on that solution -
Django Class Based UpdateView does not make any changes/Update the model it is called on
I have just started learning Django and was trying to create a simple blog website, but for some reason, I am unable to update my blog though UpdateView. Every time I hit the submit button from the update blog page, it takes me back to the detail view page without making any changes. Apart from UpdateView, rest seems to work fine like CreateView, DeleteView, ListView. Here is the code for views.py- def Category_Count(): catagories = Post.objects.values('Categories__title').annotate(Count('Categories__title')) return categories def index(request): post = Post.objects.filter(featured=True).order_by('-date_added') latest=Post.objects.order_by('-date_added')[0:3] context={'object':post,'latest':latest} return render(request,'posts/index.html',context) def Search(request): q_set1 = Post.objects.all() q_set2 = User.objects.all() query = request.GET.get('q') if query: result = q_set1.filter( Q(title__icontains = query) | Q(Content__icontains = query) ).distinct() else: result = '' context={'result':result} return render(request, 'posts/Search.html',context) class BlogListView(ListView): model = Post template_name = 'posts/blog.html' ordering=['-date_added'] def get_context_data(self, *args, **kwargs): CatCount = Category_Count() context = super(BlogListView, self).get_context_data(*args, **kwargs) context['latest'] = Post.objects.order_by('-date_added')[0:3] context['Category_Count'] = CatCount return context class PostDetailView(DetailView): model = Post template_name = 'posts/post.html' context_object_name = 'obj' form = CommentForm def get_object(self): obj = super().get_object() if self.request.user.is_authenticated: PostView.objects.get_or_create(user=self.request.user,post=obj) return obj def get_context_data(self, *args, **kwargs): CatCount = Category_Count() context = super().get_context_data(*args, **kwargs) context['latest'] = Post.objects.order_by('-date_added')[0:3] context['Category_Count'] = CatCount context['form'] = self.form return context def post(self, request, *args, **kwargs): form … -
Django View Problem. Filtered Tickets Are Not Appearing
I'm currently working on a project in Django that is a "bug tracker" or "ticket tracker" as some might call it. The goal here is to create a post or "ticket" that details a bug in the website or software for a development team. Each "ticket" has general information like name, summary, etc. but also has a "category" for the software languages or bug type(Think like categories for a blog). Every ticket also has a "priority", that is developed in a similar way as to the categories, based on the severity of the bug that a reporter encounters. I have already developed a way to click on a category name and view a list of tickets within the same category. This is successful and it works great! Naturally, my next step in the process is to use that same method of implementing ticket priorities. My goal is to be able to click on a priority and see a filtered view of all "severe" tickets with that priority, just like how my categories are set up. Here is my problem: When I click on a priority (low, medium, high, & severe), it will take me to my ticket_priority.html template for that … -
Creating multiple model objects in a single form
I have a multiple choice personality quiz that I am building in Django. The questions are pre-existing in a database, and the template loops through to display them. I've separated the Question and Response models, and I don't want to use {{form.as_p}} at all in my template. My relevant models are as follows: class Question(models.Model): question_text = models.CharField(max_length=100) question_number = models.CharField(max_length=4, unique=True) def __str__(self): return f'{self.question_number}' class Response(models.Model): question = models.ForeignKey('Question', on_delete=models.CASCADE, related_name='response') value = models.FloatField(max_length=5, default='0.0', choices = CHOICES) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='response') As this is a personality quiz, I found it easier to get my desired results by separating the Questions and Responses. My template handling the form looks like this: {% for question in questions %} <form role="form" method="POST" autocomplete="off" class="responseForm"> {% csrf_token %} <div class="col "> <table style="border-radius: 21px;"> <p style="font-weight: 500;" class="question-text">{{ question.question_text }} </p> <tr class="bubbles"> <td class="bubble-text-left">Not interested&nbsp;</td> <td> <label class="container"> <input type="radio" name="value" value="0"> <span class="checkmark"></span> </label> </td> <td> <label class="container"> <input type="radio" name="value" value="25"> <span class="checkmark"></span> </label> </td> <td> <label class="container"> <input type="radio" name="value" value="50"> <span class="checkmark"></span> </label> </td> <td> <label class="container"> <input type="radio" name="value" value="75"> <span class="checkmark"></span> </label> </td> <td> <label class="container"> <input type="radio" name="value" value="100"> <span class="checkmark"></span> </label> … -
error when i migrate ValueError: Related model 'main.user' cannot be resolved
So i was creating a custom django user model with AbstractBaseUser and an custom account manager with BaseUserManager , here is my code in models.py class MyAccountManager(BaseUserManager): def create_user(self, email,password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=250, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = MyAccountManager() def __str__(self): return self.email # For checking permissions. def has_perm(self, perm, obj=None): return self.is_admin # For which users are able to view the app (everyone is) def has_module_perms(self, app_label): return True and this on my settings.py AUTH_USER_MODEL = 'main.User' and when i do "python3 manage.py migrate" this error appears: ValueError: Related model 'main.user' cannot be resolved -
Django JSignature Not Showing Signature Input
Hi I'm trying to include django jSignature into my project. I have followed all the necessary setup steps according to the pypi. My issue is that the jSignature input is not displaying in my template when it's rendered. I can see that I'm getting an error in the javascript, but I have NO CLUE how to fix that. I don't even have the particular js file saved locally on my computer. I can see why there is an error because something in the js file is not code, but I am only loading that script through {{form.media}} it is nowhere in my local directory. Here is my code and the error: ERROR sign.html <html> <head> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <body> {{form.media}} <form> {{form}} </form> </body> </html> models.py class Sign(models.Model): sign = JSignatureField() forms.py class SignForm(forms.ModelForm): class Meta: model = Sign urls.py url(r'sign/$', SignView, name='SignView'), views.py def SignView(request): if request.method=='POST': print('post') form = SignForm() context = { 'form': form, } return render(request, 'sign.html', context) fields=('sign',) -
Unit testing Django model with an image - Not quite understanding SimpleUploadedFile
I'm a testing noob and I'm trying to figure out how to write a test to confirm that a model form is valid and will generate a new instance of Post, which is a model that has an image field. I looked some other SO posts, and it looks like I should be using SimpleUploadedFile to mock the image field. I'm having a hard time understanding how SimpleUploadedFile works (haven't found any straightforward documentation for this application), and different SO posts use some different looking syntax. Am I supposed to point to a real file path to an actual image that is held somewhere in my Django app, or does this create a fake file to be used? tests.py class CreatePost(TestCase): def test_create_post(self): data = { "content": "This is a post, I'm testing it out" } files_data = { "image": SimpleUploadedFile(name='test_image.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg') } response = self.client.post("/new", data=data, files=files_data) self.assertEqual(Post.objects.count(),1) self.assertRedirects(response, 'index') models.py class Post(models.Model): content = models.CharField(max_length=260) timestamp = models.DateTimeField(auto_now_add=True) posted_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") liked_by = models.ManyToManyField(User, blank=True, related_name="liked_posts") image = models.ImageField(upload_to='uploads/', verbose_name='image') def __str__(self): return f"{self.posted_by} posted {self.content} at {self.timestamp}" def is_valid_post(self): return len(self.content) <= 260 and len(self.content) >= 0 class Post_form(ModelForm): class Meta: model = … -
Getting Django server to subscribe to another Django server with Channels WebSockets
I am trying to work out how I can get Django Server B(IOT device) to subscribe to Django Server A (cloud) using Channels WebSockets. This is so that I can pass data async between them. Server B will be on an IOT device and Server A will be cloud-based. I've been looking everywhere, but most of the online tutorials and documentation seems to be based on subscribing(client-side) with Javascript. Surely there must be a way to subscribe with Python! Most of the online tutorials seem to be for chat apps too. It would be great if someone could help please. I'm sure there are other people looking for this same answer too. Thank you :) -
how to use alertify js with django
hi i need to use alert message when some wants delete a post ask her/him to delete or cancel i tried this but this is a default alert browser <button onclick="return confirm('are you sure you want to delete {{obj.title}}')" class="bt mx-auto"><a href="{% url 'posts:post-detail' obj.id %}"><img src="{% static 'icons/delete.svg' %}" alt=""></a></button> i want to use this alert alertify.prompt("are you sure you want to delete ", "{{obj.title}}", function(evt, value ){ alertify.success('Ok: ' + value); }, function(){ alertify.error('Cancel'); }); but i'm not sure where should i put that script in the template ? i use it inside the button to delete replacing to confirm() but seems doesnt work thanks for helping .. -
How to do connection/ migrations between different MySQL databases and Different Django App's?
I am new to Django, would be great if you could help me or correct me. please let me know what mistakes i am making. can someone give me an example with at least 2 apps and 2 Databases. I have 3 apps cherry, apple and mango in my Django project. For every app there is "models_cherry.py, models_apple.py and models_mango.py". I have created 3 databases in MySQL workbench DBtable1, DBtable2 and DBtable3. Connection between Django project and MySQL is already done. When i fires following queries on windows PowerShell for migrations, **it should create tables in the databases. python manage.py makemigrations 2) python manage.py migrate** The above command create tables for only one model for one database. My Question is, i want to create tables for all the models for all respective databases. i.e. For classes in file models_cherry.py into database DBtable1, for classes in file models_apple.py into DBtable2 and for classes in models_mango.py into DBtable3? Here are some screenshots of settings.py and routers file: settings.py core_router.py man_router.py -
OSError: no library called "cairo" was found. django anaconda environment problem
File "", line 219, in call_with_frames_removed File "C:\Users\Mamun Khan\Desktop\Python Practice\my_django_stuff\myshop\orders\urls.py", line 2, in from . import views File "C:\Users\Mamun Khan\Desktop\Python Practice\my_django_stuff\myshop\orders\views.py", line 12, in import weasyprint File "E:\AnacondaNew\envs\MydjangoEnv\lib\site-packages\weasyprint_init.py", line 375, in from .css import preprocess_stylesheet # noqa File "E:\AnacondaNew\envs\MydjangoEnv\lib\site-packages\weasyprint\css_init_.py", line 29, in from . import computed_values File "E:\AnacondaNew\envs\MydjangoEnv\lib\site-packages\weasyprint\css\computed_values.py", line 16, in from .. import text File "E:\AnacondaNew\envs\MydjangoEnv\lib\site-packages\weasyprint\text.py", line 18, in import cairocffi as cairo File "E:\AnacondaNew\envs\MydjangoEnv\lib\site-packages\cairocffi_init_.py", line 50, in ('libcairo.so', 'libcairo.2.dylib', 'libcairo-2.dll')) File "E:\AnacondaNew\envs\MydjangoEnv\lib\site-packages\cairocffi_init_.py", line 45, in dlopen raise OSError(error_message) # pragma: no cover OSError: no library called "cairo" was found cannot load library 'C:\msys64\mingw32\bin\libcairo-2.dll': error 0xc1 cannot load library 'libcairo.so': error 0x7e cannot load library 'libcairo.2.dylib': error 0x7e cannot load library 'libcairo-2.dll': error 0xc1 I follow every instruction also set the path, but i faced this problem again and again. Please help me to solve this issue. -
Django Model Not Saving All Data From Form
I currently have a Django form that saves data from a questionnaire against a user, where a user is stored as a Foreign Key from the Person model. I can successfully find the person from the Person class using get_object_or_404(), but when I try to save(commit=True), the data is not being saved in the database. See below for my code: # models.py class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=254, primary_key=True) tel_number = models.CharField(max_length=13, blank=True) referral_code = models.UUIDField() class Meta: verbose_name_plural = 'People' def __str__(self): return str(self.referral_code) class Questionnaire(models.Model): user = models.ForeignKey(Person, related_name='questionnaire_person', on_delete=models.CASCADE) ... and some questionnaire questions here (CharFields and TextFields) ... # views.py def index_questionnaire(request): template = 'questionnaire.html' # load blank instance of template questionnaire = UserQuestionnaire() context = { "questionnaire": questionnaire } # if user has submitted something, check form is valid if request.method == 'POST': answers = UserQuestionnaire(data=request.POST) if answers.is_valid(): # submission is genuine so save as new entry to database # get user's unique referral ID from URL user_referral_id = request.GET.get('user') # check legit person try: answers.save(commit=False) answers.person = get_object_or_404(Person, referral_code=user_referral_id) print('user found: {}'.format(answers.person)) answers.save(commit=True) print('Questionnaire saved') except: print("user not found") return render( request, template, context ) #forms.py class UserQuestionnaire(forms.ModelForm): class … -
Iterate over ManyToMany field Django
I am having some problems with iterating over a ManyToMany field. I want to have a Post and Tag model, and have the Post model extend the Tag model in the form of a ManyToMany relation. Below are both my Tag and Post models. class Tag(models.Model): name = models.CharField(max_length=100) def __str__(self): return f"{self.name}" class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) content = RichTextField() timestamp = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True,default="",max_length=1000) tag = models.ManyToManyField(Tag,related_name='tags',blank=True) # .... other non related functions However, when I am in the Django shell, I can't seem to loop over these tags, despite the object having tags associated to it. For example, I would do post1 = Post.objects.all()[0], and then post1.tag.name.all(), however it would give me an error saying "AttributeError: 'NoneType' object has no attribute 'all' Everything else I have tried failed. What can I fix to solve the issue? Thank you in advance -
Django App ASGI server developement mode error
I am trying to add async views to an existing Django app by updating the Django to 3.1. I tried uvicorn and daphne to run the django app, but getting the error below. But when I create a new Django app it runs fine. 2020-08-18 19:09:21,151 INFO Starting server at tcp:port=8000:interface=127.0.0.1 2020-08-18 19:09:21,151 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2020-08-18 19:09:21,151 INFO Configuring endpoint tcp:port=8000:interface=127.0.0.1 2020-08-18 19:09:21,152 INFO Listening on TCP address 127.0.0.1:8000 2020-08-18 19:09:27,164 ERROR Exception inside application: request_started_handler() missing 1 required positional argument: 'environ' Traceback (most recent call last): File "/Users/xxxxxx/virtualenvs/oath_tools/lib/python3.8/site-packages/daphne/cli.py", line 30, in asgi await self.app(scope, receive, send) File "/Users/xxxxxx/virtualenvs/oath_tools/lib/python3.8/site-packages/django/core/handlers/asgi.py", line 154, in __call__ await sync_to_async(signals.request_started.send, thread_sensitive=True)(sender=self.__class__, scope=scope) File "/Users/xxxxxx/virtualenvs/oath_tools/lib/python3.8/site-packages/asgiref/sync.py", line 296, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/tasks.py", line 455, in wait_for return await fut File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/concurrent/futures/thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "/Users/xxxxxx/virtualenvs/oath_tools/lib/python3.8/site-packages/asgiref/sync.py", line 334, in thread_handler return func(*args, **kwargs) File "/Users/xxxxxx/virtualenvs/oath_tools/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 177, in send return [ File "/Users/xxxxxx/virtualenvs/oath_tools/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 178, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) TypeError: request_started_handler() missing 1 required positional argument: 'environ' 127.0.0.1:58558 - - [18/Aug/2020:19:09:27] "GET /" 500 453 -
Django Rest Framework nested serializer gives attribute error
I am trying to setup a nested serializer below I've posted the models and serializer. why am I getting the below error ? Got AttributeError when attempting to get a value for field `balance_sheet` on serializer `StockSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Stock` instance. Original exception text was: 'Stock' object has no attribute 'balance_sheet'. serializers.py class StockSerializer(serializers.ModelSerializer): income_statement = IncomeStatementSerializer(many=True) balance_sheet = BalanceSheetSerializer(many=True) cashflows_statement = CashflowsStatementSerializer(many=True) def create(self, validated_data): temp_income_statement_data = validated_data.pop("income_statement") temp_balance_sheet_data = validated_data.pop("balance_sheet") temp_cashflows_statement_data = validated_data.pop("cashflows_statement") new_stock = Stock.objects.create(**validated_data) for i in temp_income_statement_data: IncomeStatement.objects.create(**i, ticker=new_stock) for x in temp_balance_sheet_data: BalanceSheet.objects.create(**x, ticker=new_stock) for y in temp_cashflows_statement_data: CashflowsStatement.objects.create(**y, ticker=new_stock) return new_stock IncomeStatementSerializer, BalanceSheetSerializer and CashflowsStatementSerializer are all typical ModelSerializer's models.py class Stock(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) ticker = models.CharField(max_length=10, unique=True, primary_key=True) slug = models.SlugField(default="", editable=False) def save(self, *args, **kwargs): value = self.ticker self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) def __str__(self): return self.ticker class Meta: verbose_name = "stock" verbose_name_plural = "stocks" ordering = ["ticker"] IncomeStatement, BalanceSheet and CashflowsStatement are all typical models.Model with a ForeignKey relationship to Stock views.py class StockList(generics.ListCreateAPIView): queryset = Stock.objects.all() serializer_class = StockSerializer lookup_field = "slug" -
Redirect problems with django form in a modal
I am trying to implement a form in a modal which is focused on modifying a comment in a post, the way i did it everything works, the problem is when I click on the submit button it sends me to the html in which I have the modal and there I edit the comment. when I try to delete the url in the action form that takes me to the second page of my form it throws the error "local variable 'form' referenced before assign", also if I put for example in form action the url of the login sends me towards There but the comment is not updated or edited. My idea is simply that when I submitting the form, the modal closes, and the page where the modal was opened from the beginning, reload or simply the comment already edited appears. if you need more information I can add it. views.py @need_analyst_role def comment_modify(request, comment_id): if 'comment_edit' in request.POST: form_comment = FormComment(request.POST) if form_comment.is_valid(): comment_text = form_comment.cleaned_data['text'] comment = ModelRiskTracking.objects.get(id=comment_id) comment.comment = comment_text print(comment.comment) comment.save() else: messages.error(request, 'Error!', extra_tags="danger") context = {} context['comment'] = ModelRiskTracking.objects.get(id=comment_id) return render(request, 'analyst_pages/comment_edit.html', context = context) modal.html <div class="modal-dialog modal-dialog-centered modal-lg" role="document"> … -
The current path, {% url 'requirement_post_vote' post_id=page_obj.pk vote_now='like' %}, didn't match any of these
I am learning Django and am currently trying to use a like and dislike buttons in my blog. I get the error "The current path, {% url 'requirement_post_vote' post_id=page_obj.pk vote_now='like' %}, didn't match any of these." urls.py from django.urls import path from .views import ( Requirement, UpdatePost ) from . import views urlpatterns = [ path('', Requirement.as_view(), name='flash-home'), path('requirement/<int:post_id>/<str:vote_now>', UpdatePost.as_view(), name='requirement_post_vote'), ] here is html code {% if request.user in page_obj.dis_likes.users.all %} <!-- already liked--> <a href="{% url 'requirement_post_vote' post_id=page_obj.pk vote_now='like' %}"> <i data-toggle="tooltip" data-placement="bottom" title="i dislike this" class="fa fa-thumbs-down pr-2"> <span>{{ page_obj.get_total_dis_likes }}</span> </i> </a> {% else %} <!-- not liked--> <a href="{% url 'requirement_post_vote' post_id=page_obj.pk vote_now='dis_like' %}"> <i data-toggle="tooltip" data-placement="bottom" title="i dislike this" class="fa fa-thumbs-down pr-2"> <span>{% if page_obj.get_total_dis_likes %}{{page_obj.get_total_dis_likes}} {% else %} 0 {% endif %} </span> </i> </a> {% endif %} please help am real have a big trouble because my day wasn't end well -
Retrieve an html code from database and store it in a javascript variable (with no escaping)
An html code is stored in database; for example: <p>django is <strong>good</strong></p> In the template when I want to store it in a javascript variable, it store with escaped mode and the javascript "unescape" function is not helpful. -
Django URL order
iam stuck again I hope I will get useful help this time too. Iam trying to run the app but it gives me URL configuration error something like this: Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order: admin/ products/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I see a similar query in this platform but I couldn't find my answer Iam using Django version 2.1 My code in pyshop.urls is: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('products/', include('products.urls')) ] -
Django: How to make custom ordering for this Django queryset?
I have a model called 'Format', and another called 'Department' in my Django project. I also have this model: class DepartmentFormat(models.Model): department = models.ForeignKey(Department, on_delete=models.CASCADE) format = models.ForeignKey(Format, on_delete=models.CASCADE) status = models.ForeignKey(FormatStatus, on_delete=models.CASCADE, null=True, default=None) This object may or may not exist for every specific Format object. Not always will there be a DepartmentFormat object which has assigned every existing Format. The FormatStatus class looks like this: class FormatStatus(models.Model): STATUS_CHOICES = ( (0, 'Received'), (1, 'Accepted'), (2, 'Rejected') ) status = models.IntegerField(choices=STATUS_CHOICES, default=0) description = models.TextField(max_length=80, blank=True, null=True) date = models.DateTimeField(auto_now=True) I want to order all of the Format objects like this: First, all Format objects for which there isn't a DepartmentFormat object that has them, or all those who do have one, and the status in FormatStatus is 0. The order here doesn't matter. Finally, those Format objects for which there is a DepartmentFormat object whose status is either 1 or 2. I don't know how to do this. I know the department I'm searching, but not which DepartmentFormat objects exist for each Format object. I tried this in my view: def get_queryset(self, **kwargs): qs = super(ReviewedTableView, self).get_queryset() department = self.request.user.department dpt_fmt = DepartmentFormat.objects.filter(department=department) format_ids = [] for obj …