Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove settings.MEDIA_ROOT from file path
I have code which creates a thumbnail for videos as they are uploaded - it looks like this: views.py post method: if form.instance.thumbnail == 'images/clearpath_logo/Logo.jpg': thumb_title = form.instance.title.replace(" ", "") in_path = str(settings.MEDIA_ROOT) + "/" + str(form.instance.video_file) out_path = str(settings.MEDIA_ROOT) + "/images/" + thumb_title + ".png" if create_thumbnail(in_path, out_path): form.instance.thumbnail = "images/" + thumb_title + ".png" where create_thumbnail is the helper function.. it looks as such: def create_thumbnail(input_path, output_path): """ Save first frame of video for use as video thumbnail. :param input_path: video input path :param output_path: image output path :return: Boolean """ cap = cv2.VideoCapture(input_path) ret, frame = cap.read() if ret: return cv2.imwrite(output_path, frame) else: pass My main concern here is removing settings.MEDIA_ROOT from each of the file paths. How can I avoid manually typing out the file paths as such? -
Django "Module 'django.db.models' has no 'TextFeild' member"
Hello Stackoverflow community. I started learning Django today and when I want to create module named "Products" I get this error. from django.db import models # Create your models here. class Product(models.Model): title = models.TextField() descrition = models.TextField() price = models.TextFeild() I get this error : Module 'django.db.models' has no 'TextFeild' member Please help. -
Dynamic number of list is showing errorin django pagination?
list = request.GET.get('list') paginator = Paginator(categories_list, list) int() argument must be a string, a bytes-like object or a number, not 'NoneType' -
How to display __str__ method in template in Django?
I have the following models: class Work_Music(MPTTModel, Work): name = models.CharField(max_length=10, null=True, blank=True) class Cast(models.Model): name = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.name class WorkCast(models.Model): work = models.ForeignKey(Work_Music, verbose_name=_('work'), related_name='workcast', null=True, blank=True, on_delete=models.PROTECT) cast = models.ManyToManyField(Cast, verbose_name=_('cast'), related_name='workcast', blank=True) def __str__(self): return "%s" % ( ", ".join(character.name for character in self.cast.all()) ) This will output: Character #1, Character #2, Character #3. I pass in my view.py this QuerySet as context: work = Work_Music.objects.get(pk=self.kwargs['pk']).get_descendants(include_self=False) How do display the string that is returned when you call an instance of the WorkCast model (e.g. "Character #1, Character #2, Character #3")? I have this currently: {{ work.workcast }} and it displays None -
Solr not working with DJango 2.2 and Python 3.6.9
File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/haystack/backends/solr_backend.py", line 138, in search raw_results = self.conn.search(query_string, **search_kwargs) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/pysolr.py", line 742, in search response = self._select(params, handler=search_handler) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/pysolr.py", line 437, in _select return self._send_request('get', path) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/pysolr.py", line 412, in _send_request raise SolrError(error_message % (resp.status_code, solr_message)) pysolr.SolrError: Solr responded with an error (HTTP 404): [Reason: Error 404 Not Found] SO I get that error, I Want to know what wrong am doing? something wrong when I do bash update-solr-schema.sh? -
Django test order, --failfast, and TransactionTestCase
This is a "is this possible in Python or do I have to write a shell script" question: My application has three parts: a Django app (1.11 but the operative behavior here appears to be the same in 3) a semantic parser a MySQL knowledge base, shared by both Roughly speaking, Django puts things into the KB, and runs a series of queries against the semantic parser. The semantic parser reads from the KB to inform the query results. Django and the KB are old friends; Django and the semantic parser are old friends; the integration between the semantic parser and the KB is new. If I use the Django default TestCase, the semantic parser can't see any intermediate changes to the knowledge base made during the test, because the whole test is wrapped in atomic() by Django. This is a bummer, but fine: the tests where the semantic parser has to read from the database now inherit from TransactionTestCase. The problem is, we're a research shop, and we frequently experiment with new techniques that break low-level behaviors. I used to have a carefully-ordered TestSuite of 50+ tests that starts with the simple building blocks and builds up in complexity … -
Untrackable NoneType is not callable error in Django
I've been staring at this traceback for three hours and can't for the life of me figure out where the "NoneType" error is. I can't find any functions being called from variables (e.g. def run(f): f()), which as far as I understand is what the error is supposed to be reporting. Do I have a null object hiding somewhere? http://dpaste.com/2XW17JS -
Why does this assert_has_calls with the usage of ANY fail in python 3 but not in python 2?
It looks like the version of the mock is 3.0.5 in both Python 2.7.15 and 3.7.5 I am testing in. with patch('a.models.BManager.methodC',autospec=True) as method_mock: do something expected_calls = [ call(ANY, param_a=some int value, param_c=some datetime value, etc..), call(ANY, param_a=some int value, param_c=some datetime value, etc..) ] method_mock.assert_has_calls(expected_calls, any_order=True) This succeeds in Python 2. However, in Python 3, I get (a few new lines inserted for better formatting) AssertionError: 'methodC' does not contain all of (('', <BoundArguments (self=<ANY>, param_a=1, param_b=2, param_c=datetime.datetime(2020, 1, 29, 11, 47, 11))>), ('', <BoundArguments (self=<ANY>, param_a=1, param_b=3, param_c=datetime.datetime(2020, 1, 30, 3, 47, 11))>)) in its call list, found [('', <BoundArguments (self=<a.models.BManager object at 0x7fc95ff66fd0>, param_a=1, param_b=2, param_c=datetime.datetime(2020, 1, 30, 3, 47, 11))>), ('', <BoundArguments (self=<a.models.BManager object at 0x7fc95ff66fd0>, param_a=1, param_b=3, param_c=datetime.datetime(2020, 1, 30, 3, 47, 11))>)] instead The code that's being run is: ModelClassOfBManager.objects.methodC(param_a=1, etc) Can anyone help me why this, which succeeds in Python 2, fail in Python 3? The expected calls and actual calls are exactly the same except the value for 'self' which I used ANY. -
TestCase help. AssertionError: 200 != 302
Hey guys I am trying to run some tests with the following code view @login_required def compose(request): """Form to compose a new message""" template_name = 'messaging/compose.html' form_class = MessageForm if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): form.save(sender=request.user) messages.info(request, 'Message sent successfully', extra_tags='sent') success_url = reverse_lazy('messaging:messages_outbox') return redirect(success_url) else: form = form_class() return render(request, template_name, {'form': form}) TestCase class TestMessageViews(TestCase): def setUp(self): super().setUp() self.user1 = get_user_model().objects.create(username='user1') self.user2 = get_user_model().objects.create(username='user2') self.form = create(Message, {'sender': self.user1, 'recipient': self.user2, 'subject': 'test_subject', 'body': 'test_body'}) self.client = Client() def test_compose_message(self): """Test to make sure our compose is redirecting us""" self.client.force_login(user=self.user1) response = self.client.post(reverse('messaging:messages_compose'), { 'recipient': self.user2, 'subject': self.form.subject, 'body': self.form.body }) self.assertEqual(response.status_code, 302) I am getting back a status code of 200, when this should be redirecting us to the outbox which should be a 302? -
Alter tables and columns in Django
I was trying to alter some column fields in my MySQL table by modifying the class "test" below and messed it up in a bad way, I also deleted the migration files. I am new to models and migrations but I am trying to understand on how to modify a table or columns in a proper way. 1) I have seen people modify the test class directly, for example if I would like to change the decimal_places to 5 instead of 4 they just changed the number and ran makemigrations. This is how I did it, sometimes it worked and sometimes it didn't recognize any changes. And now the last time it messed up my unique_together() function. After some research it seems that I should create a table with class test(models.Model) and then from there on If I would like to change something I should use the ALTER TABLE function? 2) Since I now have ruined a well functioning database I would like to delete my table and create a new models.py and do the setup all over again. Is this a "proper" way of doing it or is there something smoother than just DROP TABLE and deleting the models.py … -
Img of the prduct & other details like title,price etc are not showing up my code is correct .cmd says 'Not Found: /1/{{ product_object.image }}'
In this screenshot the image of the product and other details like title,price,description etc are not showing up but all of my code is correct . In command prompt it also says 'Not Found: /1/{{ product_object.image }}' What should I do? -
Add form field to template dynamically via javascript django
I'd like to add a form field to the template when the user clicks on a button via javascript. I don't want to hide it and just make it appear, I need to insert it because it can be loaded into multiple parts. This is what I've tried but no luck. document.getElementById("div_id").value = '{{ my_form.field|as_crispy_field }}'; -
Creating dictionary with user's input
I need to create dictionary with user's selecting the checkboxes For example from [here][1] I need a dictionary like diction = {'1':['a','b'], '2':['b','c'], '3':['a','c'], '4':['c','d']} Haven't tried anything yet as I have no idea what can be done. -
Cannot access POST variable because it's wrapped in Decimal('')
I'm trying to access a POST variable form.data['amount'] but I get MultiValueDictError. The traceback shows that the amount value has some other dictionary or something inside it. Any ideas how to access the number? initial {'account': <Ledger: Agata's Account>, 'amount': Decimal('60.00'), 'date': '2020-01-29', 'store': 'Tesco'} -
Difficulty in Serializing Django rest framework
I have a serlizer like this class ArticlesSerializer(serializers.ModelSerializer): # order = OrderSerializer(read_only=True) article = ListArticleSerializer(read_only=True) article_options = ArticlesOptionSerializer(read_only=True, source='orderarticleoptions_set' , many=True) class Meta: model = OrderArticle fields = [ 'id' , 'article', 'article_options' ,'article_quantity' ,'article_prize' , 'article_total_prize'] When I Query in database and get data by Filter its working fine . Now I am creating a custom object of filter query like this order_article_list = OrderArticle.objects.filter(order__order_number=id, order__restaurant=restid) data = {} for order_article in order_article_list: data[order_article.article.category.name] = order_article.article.category.articles_set.all() serializer = ArticlesSerializer(newArray, many=True) return Response(success_response({'Articles': serializer.data }, "Description of a Order."), status=status.HTTP_200_OK) And I am getting data like {'cat1':[article1, article2], 'cat2': [article4, article5]} but when I serlize its giving errors and its not in standard query form.How I can I fix this ? -
How can I fix a problem with runing conda django virtual enviroment?
Can anyone help me with following problem? I encountered that during one of the courses I am taking. I use ios Catalina 10.15 therefor I use zhs as bash is no longer supported by mac I am trying to run virtual server so I can see my webpage I managed to run the virtual server once only (python manage.py runserver) and after the restart I have problem with it eversince. > first_proj python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?``` when I check for django (django-admin --version), turns out it is installed, I am getting this ouput: 2.2.5 (version of Django installed). my django directory is: /Users/myname/opt/anaconda3/envs/projectname/lib/python3.8/site-packages/django maybe it is something about the directory django is installed (?) thanks for any help. -
Using Django to connect to external database in order to compensate for deprecated dynamic models support
Right now I trying to implement some functionality to a website I am designing. I want the users able to have some functionality which is equivalent to creating tables in a SQL database. In order to do this in Django, I would need to use dynamic model support which is deprecated. I am considering just working outside the Django ORM and using a MySQL database. The database client and accompanying functionality would then just be called from the appropriate views.py file. Is this advisable and what other approaches could be used? -
Return usernames mentioned in post as profile links to those users inside the post
Hey guys I'm trying to get my code to check for a user mentioned in a post with @username that is in the database and return that users profile link as the @username. I am currently able to get the users in the backend with the tagged_users variable in my views. It store the users mentioned but how do I access that in the template so that it gives me the link to those users profiles? so far my code is this in the template {% if post.post|slice:":1" == '@' %} <a href="{% url 'profile_with_pk' pk=user.username %}"> {{ post.post }} </a> {% else %} {{ post.post }} {% endif %} this returns the entire post as a link but does not return the actual user mentioned in the post instead it makes a link to the current user logged in This is my code that brings back the users mentioned in the tagged_users list correctly I want to access this in the template as a link to those users profiles in the post. def post(self, request, pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user form = HomeForm(request.POST) users = User.objects.all() if form.is_valid(): post = form.save(commit=False) post.user = request.user … -
How to save the database created in the docker?
So I am following the official documentation django with postgres in docker https://docs.docker.com/compose/django/ I created another database, ( not using the default postgres db ). but when shutdown the server and re run it, It doesn't show the database. How can i create database so that it doesn't vanish when i shut down my docker server. -
DRF Serializer queryset filtering cross tables
I'm using Django REST Framework to configure Experiments that are carried out using different logins for different Services. How can I adjust the queryset of the set of BasicLogins depending on the chosen Service. Context When configuring an Experiment, you chose a Service and multiple participating BasicLogins. There are specific logins that are 1-to-1 related to a BasicLogin. Let's say we have BasicLogin, ALogin, BLogin and CLogin. It can happen that not all specific Logins exist for a given BasicLogin, e.g. BasicLogin 1: has related Logins for Services A and B BasicLogin 2: related Logins for Service C BasicLogin 3: has related Logins for Services A, B, C BasicLogin has a supports method which looks up if a Service-specific login is related to it. If such specific Login object exists, the BasicLogin object supports the given Service. class BasicLogin(models.Model): name = models.CharField(max_length=25) password = models.CharField(max_length=25) disabled = models.BooleanField(default=False, blank=True) def supports(self, service_name): """ Returns whether a specific Login for a given service is available for a BaseLogin object.""" if service_name == "a": return ALogin.objects.filter(basic_account=self) is not None elif service_name == "b": return BLogin.objects.filter(basic_account=self) is not None elif service_name == "c": return CLogin.objects.filter(basic_account=self) is not None The ExperimentSerializer can easily be … -
How to override a Django url path that is provided by a library?
I'm currently building out an authentication server using Django, djangorestframework, and django-rest-auth. My problem is actually pretty simple I think, but I haven't really been able to find any resources on it. Here's my issue, in django-rest-auth there is a specific url to change a user's password, which is /rest-auth/password/reset/. I'd like the url to instead be /auth/password/change/, but don't want to edit the library code to do so. The issue is that as of now, in my url.py file, I have the rest-auth urls imported as such: from django.urls import path, include urlpatterns = [ path('', include('rest_auth.urls')), ] So it just imports the urls as written in the library. How can I change the specific url to what I want? -
Reduce code and database redundancy between multiple Django projects
I have multiple Django projects that have commonalities in their code and databases, how can I merge the commonalities into a core project to reduce redundancy? The best solution I can think of is to make each project to communicate with the core one through http, but this would decrease the efficiency. I also need to store users into the core project so using http would even be less safe. I also read about Django Rest Framework, maybe I should use it as part of the solution. -
How to generate a list from a many-to-many model?
I have the following models: class Cast(models.Model): name = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.name class WorkCast(models.Model): work = models.ForeignKey(Work_Music, verbose_name=_('work'), related_name='workcast', null=True, blank=True, on_delete=models.PROTECT) cast = models.ManyToManyField(Cast, verbose_name=_('cast'), related_name='workcast', blank=True) I am trying to generate a list: Cast member #1, cast member #2, cast member #3 from the WorkCast model: I tried adding this to the model, but nothing is generated. What is wrong? def __str__(self): return "%s" % ( self.cast, ", ".join(cast.name for self.cast in self.cast.set()), ) -
Creat REST Api Using Django Rest Framework
I am trying to create a Restful Api for following methods to run jenkins jobs to run on saucelabs. I wanna queue jobs using restful API. I am using Django Restful Framework. CreateMethod : Accepts two fileds: ProjectName and URL and returns a Token ID. VerifyStatus: Accepts Token ID and returns three fields. TokenID, running:True/False and no_of_jobs: integervalue (0 if Not specified) relseaseMethod: Accepts release token call and returns true if success. I am new to Restful API with, I am trying to run Jenkins job on sauce lab and queue them using a restful api on python Djano restframework. Guide me through. -
Django rest framework viewset get_queryset() doesn't return correct queryset
I am working with Django Rest Framework Filter to access my data. I wrote a custom viewset for one of my models to handle logical 'or' operation on some specifics fields for request with url. Here is my code (the printing are just for my debug) class CustomViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = appart.MyModel.objects.order_by('pk') serializer_class = MyModelSerializer filter_class = MyModelFilter def get_queryset(self): # getting param query = dict(self.request.query_params) print(query) ct_query = query['caracteristique_text__icontains'][0].split('|') cl_query = query['caracteristique__libelle__in'][0].split(',') # writting request syntax ct = 'Q(caracteristique__libelle__in=' + str(cl_query) + ')&(' print(ct) for value in ct_query: ct += "Q(caracteristique_text__icontains='" + value + "')|" ct = ct[0:len(ct) - 1] ct += ')' print(ct) filtre_text = "global filtre; filtre = " + ct # creating the request exec(filtre_text) #running the request self.queryset = self.queryset.filter(filtre) print(self.queryset) return self.queryset # doesn't return what I see when running print(self.queryset) this code is working well and do what I want it to do. He takes the url parameters, create dynamically the request syntax and return the data i'm looking for. The only problem is that the return at the end doesn't give the same result that what I printed in my code. He still trying to execute a GET request based …