Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
All my django project files has been duplicated after some git commands
Please help !!! I was trying some git commands (I'm not used to it) to push my django project on a repo on github. I initiated git, then created a repo on github. I had some strange difficulties to do the push command but finally I got it. The problem is that all of my project files has been duplicated. I am really confused and some how in panic. don't know what to do. For example I have "admin.py" AND "admin 2.py" and so on. If it was a few files, I could have deleted duplicates manually, but I have every thing duplicated : static files, template files, migrations... and so on (hundred of files) I'm not sure which command or what caused this. Could any one rescue me please ? I've reverted my repo to the initial commit but those copies are still there. -
Full-stack development
I'm new to the web development and I literally stucked on the main problem. I've made a frontend (bootstrap) using website builder Pinegrow (I have an access to the javascript code) and the thing is that I need to build a backend for it. I do have skills in python so I decided to use Django framework. Is it possible to combine frontend which is made by this way with Django backend? -
Django models.Manager unable to access model
I have the following test which fails as it only inserts one row into the database where it should be inserting 100 rows class QuestionsTest(TestCase): def setUp(self): self.fake = Faker() def test_populating_table_with_random_data(self): newQuestion = Questions() x = 0 while x < 100: newQuestion.category = self.fake.text(max_nb_chars=254) newQuestion.difficulty = self.fake.text(max_nb_chars=8) newQuestion.question_type = self.fake.text(max_nb_chars=20) newQuestion.text = self.fake.text(max_nb_chars=254) newQuestion.save() x += 1 #100 rows should be inserted self.assertEqual(Questions.objects.count(), (100)) """Traceback (most recent call last): File 'Database/tests.py', line 99, in test_populating_table_with_random_data self.assertEqual(Questions.objects.count(), (100)) AssertionError: 1 != 100 """ Prior to receiving this error I was getting the error "Class Questions has no objects member". I got around this by explicitly declaring objects = models.Manager() in my Questions model, but I thought that django automatically generated a manager with the name objects -
How to Query ManyToMany django to find all instances?
I am trying to query to find all instances of User that is associated with self (a Venue). User is an extended AbstractBaseUser. This is how I declare stuff: class Venue(models.Model): administrators = models.ManyToManyField(get_user_model(), related_name="administrators_set") def save(self, *args, **kwargs): # Get all admins # Do stuff with admins super(Venue, self).save(*args, **kwargs) I have tried using admins = self.administrators.all() but get Unresolved attribute reference 'all' for class 'ManyToManyField' -
NoReverseMatch at /password_reset_complete/ 'users' is not a registered namespace
urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register , name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logged_out.html'), name='logout'), path('password_reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'), path('', include('learning_logs.urls')), ] password_reset_confirm.html: {% extends "learning_logs/base.html" %} {% load bootstrap4 %} {% block page_header %} <h2>Reset your password.</h2> {% endblock page_header %} {% block content %} <form method="post"> {% csrf_token %} {% bootstrap_form form %} <button type="submit" class="btn btn-primary">Submit</button> </form> {% endblock content %} password_reset_complete.html: {% extends "learning_logs/base.html" %} {% block content %} <p>Password changed </p> <a href="{% url 'login' %}">Sign in</a> {% endblock content %} I've tried to find the reference to namespace 'users' which the error is referring to. But I have no idea where is the source. I get this error whenever I fill in password_reset_confirm fields for resetting the password. Any ideas? -
GDALException at /admin/shops/shop/add/ OGR failure
I was trying to manually add some data. But I keep getting this error message. I have tried to get help from GIS/Gdal/OSGeos Import error in django on Windows GeoDjango GDALException - OGR failure I am unsure if it is necessary to set GDAL_LIBRARY_PATH and if it is, have I done it properly? I have no idea what the difference between gdal111.dll and gdal300.dll is. settings.py import os if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] GDAL_LIBRARY_PATH = 'C:\\OSGeo4W64\\bin\\gdal111.dll' import django_heroku -
Django Query with Case Insensitive Data Both Ways
There are a lot of similar questions, but I'm only finding partial solutions. I have a group of users stored as objects, with a name attribute (User.name). I'm hoping to do a query with a user input (Foo) such that I can (without being case sensitive) find all users where either: foo is in User.name User.name is in foo As an example, I want the user to be able to type in "Jeff William II" and return "Anderson Jeff William II", "jeff william iii", as well as "Jeff Will" and "william ii" I know I can use the Q function to combine two queries, and I can use annotate() to transform User.name like so (though I welcome edits if you notice errors in this code): users = User.objects.annotate(name_upper=Upper(name)).filter(Q(name_upper__icontains=foo) | Q(name_upper__in=foo)) But I'm running into trouble using __in to match multiple letters within a string. So if User.name is "F" I get a hit when inputting Jeff but if User.name is "JE" then it doesn't show up. How do I match multiple letters, or is there a better way to make this query? SIDE NOTE: I initially solved this with the following, but would prefer making a query if possible. for … -
django tables 2 - delete column and delete_item for inherited tables
I want to have one abstract function for all my tablelists (one for each model) and (one delete_item) function in view. I don't know how to make the delete (column in this table) and pass the model to the delete_item function in the view Tables.py ''' ############ Abstract Table class abs_Table(tables.Table): SN = tables.Column(empty_values=(), orderable=False) delete = tables.LinkColumn('delete_item', args=[A('pk'), ?????Model???], attrs={ 'a': {'class': 'btn btn-small btn-dark'} # }) def __init__(self, *args, **kwargs): super(abs_Table, self).__init__(*args, **kwargs) self.counter = itertools.count(1) def render_SN(self, record): pg = getattr(self, 'paginator', None) if pg: v = next(self.counter) return v + self.paginator.per_page * (self.page.number-1) else: return next(self.counter) class Meta: model = None fields = [ 'SN', 'id', 'delete', ] attrs = {"class": "table-striped table-bordered", 'width': '100%'} empty_text = "There are no Records matching the search criteria..." ''' Then for model Table Tables.py ''' class ModelTable(abs_Table): class Meta(abs_Table.Meta): model = modelname fields = abs_Table.Meta.fields+[selected_model_fields] ''' Views.py ''' def delete_item(request, pk, delmodel): obj = get_object_or_404(delmodel, id=pk) if request.method == "POST": obj.delete() return redirect("../") else: pass context = { 'object': obj } return render(request, '/delete_confirmation.html', context) ''' -
How to transfer Django's messages to Angular app
I am building Django 2.2 +Node + Angular 8 app. Django is used to run a couple of simple scrapers when user clicks on Search btn. I want to make user notified that the scraping process started successfully (if it is the fact) and that the scraping is finished, or that some errors occurred. Some intermediate statuses are also desirable, but not mandatory. I thought about using django.contrib.messages, but not sure how to make my Angular app receive them. Can anybody advise me with that problem? P.S.: not sure if it is important - I want to use Angular's snackbar to make user notified about scraping statuses. -
rediecrting to a page along with a header
i want to redirect to a particular page on a button click along with the token filled in by the client as header....i tried windowns.location but it doesnt support any header carrying feature...is there an alternative to this....i checked it in cosole..the token is being stored in "token" <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST"> {% csrf_token %} <input type="text" name="token" id="token" placeholder="token"> <button type="button" onclick="myFun()"> submit </button> </form> </body> <script> function myFun(){ var token=document.getElementById("token").value; console.log(token); window.location.replace("http://127.0.0.1:8000/app/task-list",{ 'Authorization': 'Bearer ' + token}); } </script> </html> -
allow the user to change his order values in the data base
i want to allow the user to change a value in his order from the data base The idea is when the user press the delete button the value of visible changes from yes to no and he won't be able to see it on the profile i managed to pull out all the user's orders but i couldn't find a way to make the button change the value for the order of that current user only is there any way to do such thing?? models.py class Order(models.Model): status_ch = [('in process','in process'),('complete','complete')] visible_ch = [('yes','yes'),('no','no')] status = models.CharField(choices=status_ch,max_length=20,null=True,blank=False,default='in process') user = models.ForeignKey(User,on_delete=models.CASCADE,null=True, blank=True) saller = models.CharField(blank=True,max_length=200) product = models.CharField(blank=True,max_length=200) currency = models.CharField(blank=True,max_length=200) name = models.CharField(max_length=200,null=True,blank=False) phone = models.FloatField(null=True,blank=False) amount = models.FloatField(null=True,blank=False) email = models.EmailField(null=True,blank=True) accountId = models.TextField(default='',blank=False) date = models.DateField(default= datetime.date.today) image = models.ImageField('Label') visible_for_saller = models.CharField(choices=visible_ch,max_length=20,null=True,blank=False,default='yes') visible_for_buyer = models.CharField(choices=visible_ch,max_length=20,null=True,blank=False,default='yes') def __str__(self): return self.saller views.py @login_required def profile(request): orders = Order.objects.filter(user=request.user) return render(request,'app/profile.html',{'orders':orders}) -
How to use serialize to serialize only some field?
Suppose I have a serializer class ProductSerializer(serializers.ModelSerializer): product_brand = serializers.StringRelatedField() product_type = serializers.StringRelatedField() class Meta: model = Product fields = '__all__' I want to use the same serializer to other serializer but I only need to get the product_type from it i.e.: class ItemSerializer(serializers.ModelSerializer): product = ProductSerializer( # only get product_type) ... class Meta: model = Item fields = '__all__' The wanted result would be: { ... "product": { "product_type": "Random" } } -
I got this Error AttributeError: module 'django.contrib.gis.db.models' has no attribute 'GeoManager'
This Is My Models : class Intervention(models.Model): Titre_intervention = models.TextField(max_length=255) date_intervention = models.DateField(auto_now_add=True) type_panne = models.ForeignKey(Panne,on_delete=models.CASCADE) etat = models.CharField(max_length=30) description = models.TextField(max_length=255) image = models.ImageField(blank=True,null=True,upload_to='medial/%Y/%m/%D') equipements = models.ManyToManyField(Equipement) clients = models.ForeignKey(Client,on_delete=models.CASCADE,default=True) location = models.PointField(srid=4326) objects = models.GeoManager() And This Is What I Imports : from __future__ import unicode_literals from django.db import models from django.contrib.gis.db import models So When I Run Makemigrations I got error Of : AttributeError: module 'django.contrib.gis.db.models' has no attribute 'GeoManager' -
Djando tempus dominus modal does not work
I have installed in my app the tempus_dominus app, usuing in the following manner: from tempus_dominus.widgets import DatePicker, TimePicker, DateTimePicker class InformazioniGeneraliForm(forms.ModelForm): data_registrazione=forms.DateTimeField(widget=DatePicker(attrs={ 'append': 'fa fa-calendar', 'icon_toggle': True, })) And in my template utilized in the following manner: {{ form.media }} <div class="row"> <div class="form-group col-2 0 mb-0" > {{form.codice_commessa|as_crispy_field}} </div> <div class="form-group col-2 0 mb-0" > {{form.data_registrazione|as_crispy_field}} </div> All works great but now I have the necessity to insert a modal button in the same page. I have tried to insert the same {{form.data_registrazione|as_crispy_field}} but when I press the datepicker it opens the first form one like in the following photo: How could I solve this issue? -
Large file upload problem with Django, Android
I'm using Django-rest-framework as android server. When trying to upload a voice file(.wav) to the server in Android, if it is over 2.5MB, the following error occurs. Internal Server Error: /tts_app/train/file-upload Traceback (most recent call last): File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site- packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\pjpp8\tts_project\ttsproject\tts_app\views.py", line 47, in post new_data = request.data.dict() File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\rest_framework\request.py", line 209, in data self._load_data_and_files() File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\rest_framework\request.py", line 272, in _load_data_and_files self._data, self._files = self._parse() File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\rest_framework\request.py", line 347, in _parse parsed = parser.parse(stream, media_type, self.parser_context) File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\rest_framework\parsers.py", line 109, in parse data, files = parser.parse() File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\django\http\multipartparser.py", line 229, in parse handler.new_file( File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\django\core\files\uploadhandler.py", line 140, in new_file self.file = TemporaryUploadedFile(self.file_name, self.content_type, 0, self.charset, self.content_type_extra) File "C:\Users\pjpp8\tts_project\ttsvenv\lib\site-packages\django\core\files\uploadedfile.py", line 61, in __init__ file = tempfile.NamedTemporaryFile(suffix='.upload' + ext, dir=settings.FILE_UPLOAD_TEMP_DIR) … -
How to order by values in ArrayList in Django?
I have a model lets say products, which has a field prices that is basically an array: prices = [price on Monday, price on Tuesday, price on Thursday] How do I order products by prices on a specific day, eg: price on Monday? -
Dynamically mocking the return value of a database call in Django test
I am trying to test a function and dynamically mock out the database call to the RecordType table, as the test database does not contains all the instances that I need for the function to run. This is the part of the function in question: permanent = [] temp = [] for category in enums.Category: category_name = str(category.name) if category_name in labels: if not category.is_temporary_code: permanent.append(category) else: temp.append(category) for category in permanent: category_name = str(category.name) internal_code = models.RecordType.objects.get( industry_code=category.value ).internal_code field_label = labels[category_name] self.fields[internal_code] = forms.BooleanField(label=field_label, required=False) I have a dict of values (record_type_dict) that I would like to be returned in place of calling the mocked function, depending on the passed in 'category.value'. In my test file I have this code: @mock.patch.object(forms, 'models') def test_records(mock_models, factory, support_client): .... mock_models.RecordType.objects.get().internal_code.side_effect = side_effect ... def side_effect(*args, **kwargs): if args[0] in record_type_dict: return record_type_dict[args[0]] else: return "" However this does not work as the database is being called with 'industry_code=category.value'. Is there a way of dynamically mocking this call depending only on the value of category.value? -
Django & Bootstrap - add Spinner to form
I want to make my quantity form a little bit more appealing: My original code: {% for form in formset_parts %} <div class="row form-row spacer"> <label>{{form.name.label}}</label> <div class="input-group"> {{ form.part }} {{ form.qty }} </div> </div> {% endfor %} <div class="row spacer"> <button type="submit" class="btn btn-block btn-primary">Create</button> </div> {% endfor %} I want to changed that to something like: {% for form in formset_parts %} <div class="row form-row"> <tr> <td>{{ form.part.label }}:</td> <td> <select class="browser-default custom-select"> {% for part in form.part %} <a class="dropdown-item" href="#">{{ part }}</a> {% endfor %} </select> </td> <td>{{ form.qty.label }}: </td> <td>{{ form.qty }}</td> </tr> </div> {% endfor %} I would now like to include a spinner for the qty label, like shown here. So I copy & pasted the code from here in a file called bootstrap-input-spinner.js in the root project directory under ../static/js/bootstrap-input-spinner.js. In the template of the app I added (below the code pasted above). {% block custom_js %} <script src="{% static 'js/bootstrap-input-spinner.js' %}"></script> <script> $("input[type='quantity']").inputSpinner() </script> {% endblock %} So now instead of my {{ form.qty }} i want to use <input type="quantity" value="0" min="0" max="50" step="1"/> but I don't know how this will link to the former {{ form.qty }} … -
DjangoFilterBackend: Filtering on a primary key results in "Select a valid choice. That choice is not one of the available choices."
I have two models (Product & Category) which every product has a linked category. I have installed DjangoFilterBackend which the hope of filtering on the category field to return a list of products in that category. However, whenever I send the query in Postman. I receive the error Select a valid choice. That choice is not one of the available choices.. I have tried filtering on another field in my product model (name for an example) and that works fine. So i'm not sure if i'm missing something for category to work. Product/View.py: class ProductView(ListAPIView): serializer_class = ProductSerializer queryset = Product.objects.all() filter_backends = [DjangoFilterBackend] filterset_fields = ('category', 'name') Products/Models.py: class Product(models.Model): name = models.CharField(max_length=250, unique=True, blank=False) photo = models.ImageField(upload_to=product_photo_path) category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.IntegerField() description = models.TextField(blank=False) price = models.DecimalField(max_digits=6, decimal_places=2) in_stock = models.BooleanField(default=False) trending = models.BooleanField(default=False) def __str__(self): return self.name Products/serializers.py class ProductSerializer(serializers.ModelSerializer): category = serializers.CharField(source='category.name', read_only=True) class Meta: model = Product fields = ('category', 'name', 'photo', 'quantity', 'description', 'price', 'in_stock', 'trending') The query I am using: http://127.0.0.1:8000/api/products?category=xxxx - which results in an error. -
Django,unable to download mp3 files in frontend
My Django app have mp3 file field as mentioned in the below model. I upload mp3 files from admin side. When I send GET request for mp3 files in frontend , it plays in browser but I can't download If I attempt download it results in error as mention below in terminal and download fails MODELS.PY from django.db import models class Music(models.Model): ... track = models.FileField(upload_to='tracks') ERRORS Traceback (most recent call last): File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 279, in write self._write(data) File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "c:\users\dell\desktop\pythonfiles\Lib\socketserver.py", line 796, in write self._sock.sendall(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host [05/Jun/2020 16:33:37] "GET /media/tracks/Kalimba.mp3 HTTP/1.1" 500 59 Exception happened during processing of request from ('127.0.0.1', 59832) During handling of the above exception, another exception occurred: TypeError: 'NoneType' object is not subscriptable AttributeError: 'NoneType' object has no attribute 'split' -
Frontend application displaing progress from API
I've got a case where I have got 3 docker containers: - frontend in Angular - backend in Django - processing API in python. The use-case is that user sends a file to backend volume (using frontend GUI) and then API processes it. Processing takes some time, so API sends updates using SSE to the backend (which was a trigger for that action) and I would like to forward that progress updates to the frontend. I've tried to use WebSockets for that (frontend <-- WebSocket --> backend <-- SSE --> API), but there is a lot of bugs in case of processing multiple files at once. I also would not like to expose API to frontend. API can process multiple files in parallel. Do You guys have got some best practices for such case? -
Django, JSONField, filter for non empty list
I have a jsonfield foo = JSONField(default=list) I want to filter queryset so that foo has some data (not empty list) I've tried MyModel.objects.filter(foo__ne=[]) // doesn't seem to work MyModel.objects.filter(foo__gt=[]) // seems to work but can't be sure if it's the right approach -
django-tables How to disable clickable <th>
What is the best way to disable clickable th in django-tables? everytime i click the url change this is my views.py gradelevels = request.GET.get('gradelevel') semesters = request.GET.get('semester') sections = request.GET.get('section') table = StudentTable(StudentsEnrollmentRecord.objects.filter(Education_Levels=gradelevels).filter( Semester=semesters).filter(Section=sections).filter(Status = 'Validated')) RequestConfig(request).configure(table) export_format = request.GET.get("_export", None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table) return exporter.response("table.{}".format(export_format)) return render(request, "Homepage/Detail_report.html", {"gradelevel": gradelevel, "semester": semester,"section":section, "table":table}) this is my html <div class="container"> <table class="table"> <tr> <td>{% render_table table %}</td> </tr> </table> {% for format in table.export_formats %} <a href="{% querystring '_export'=format %}"><button>download <code>.{{ format }}</code></button></a> {% endfor %} </div> -
How can I get request data in Django from a redirect?
I need to get data from a redirect, but I can't really figure out how. The method is GET as I can see from my print. But I have tried everything I found on searching for this without luck. What am I doing wrong? I really appreciate any help. I have this redirect: return redirect('/list-view', new = 'new') My urls looks like this: path('list-view/<new>', views.list_view, name='list'), Then my list-view is: def list_view(request, *args, **kwargs): print(request.method) if request.method == 'GET': aa=request.GET.get('new') if aa: bb = (request.GET.get('new')) print (bb['new']) -
Steps In Building a Social Media With Python [closed]
I'm learning python and I want to build a social media. What are the things I should learn, what part of python should I be based on to make that a successful social media