Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use ForeignKey, ManyToManyFields and other fields of Django Relational DB into MongoDB
I am new in Django with MongoDB. Please suggest how to create models using MongoDB with relationship like ForeignKey, ManyToManyFields etc... -
Connecting js to html in django not working
I am trying to connect js to html in django. When i include script inside html file it excetutes the command, however i created seperate js file and linked to django so it does not work whereas I linked css file and it works fine , I am learning and using tutorials some of them are old and i do not know whether i am using old style and this is why linking js to django does not work. Would be happy if you could help to understand where i am doing wrong: in index.html <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static 'school/css/main.css' %}"> </head> <body> <div>{% block content %}{% endblock %} </div> <script type="text/javascript" scr="{% static 'school/js/main.js' %}"> </script> </body> </html> in settings i have : STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')] and main.js file: alert ("Hello"); My django version is my django version is 2.2.6 -
mongoengine.connection.ConnectionError: Cannot connect to database default : False is not a read preference
Django==2.2 django-rest-framework-mongoengine==3.4.1 djangorestframework==3.11.0 dnspython==1.16.0 mongoengine==0.9.0 pymongo==3.10.1 pytz==2019.3 six==1.14.0 sqlparse==0.3.1 these are the versions I am using. problems I am facing : mongoengine.connection.ConnectionError: Cannot connect to database default : False is not a read preference. again and again I am gettings this error. I want to connect to mongo atlas from my django project and then develop REST APIs for the same. solution I get: swtich to pymongo==2.8 problem: then it raises host should start with mongod:// not mongo+srv what i found pymongo 2.8 to 3.5 giving same errorS. and I am not able to resolve this error. please guide me through. for eg connect('db1223', host='mongodb+srv://admin123:'+urllib.parse.quote('admin@123')+'@enter code heresymbol-rd1il.mongodb.net/test?retryWrites=true&w=majority') what I want to accomplish is integrate django with mongo db and then develop REST APIs I have also gone through BurkovBA / django-rest-framework-mongoengine-example github repository. please please guide me.. -
Removing whitenoise form django project
I am working on a web app using django 3.0.4. Initially I was serving static files using whitenoise 5.0.1. However, now I am getting ready to put the project in production and use django storages with AWS S3 intead. I removed whitenoise from the middleware in my settings.py and uninstalled from my virtual environment as well. However when I run python manage.py runserver, I get the following error: (venv) D:\Projects\Bandar\BandarManagementPlatform>manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 09, 2020 - 15:33:04 Django version 3.0.4, using settings 'BandarManagementPlatform.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "D:\Projects\Bandar\BandarManagementPlatform\venv\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "D:\Projects\Bandar\BandarManagementPlatform\venv\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\Haamid\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\Projects\Bandar\BandarManagementPlatform\BandarManagementPlatform\wsgi.py", line 16, in <module> application = get_wsgi_application() File "D:\Projects\Bandar\BandarManagementPlatform\venv\lib\site-packages\django\core\wsgi.py", line 13, in … -
Django / Getting a specific queryset in ListView
I want to get specific queryset inside my ListView class. The queryset that I want to get is: user = User.objects.get(username=username) However, since ListView is class-based view, I can't define what I want. I tried like this: **views.py** class PostListView(ListView): model = Post template_name = 'itu_forum/home.html' context_object_name = 'posts' ordering = ['-date_posted'] # for normal view [date_posted] paginate_by = 6 def get_context_data(self, **kwargs): ctx = super(PostListView, self).get_context_data(**kwargs) ctx['title'] = 'Ana Sayfa' return ctx def get_queryset(self): queryset = super(PostListView, self).get_queryset() return queryset.filter(author.username=self.kwargs['username']) This is the url I want to use. I want to get to specific user's profile: **urls.py** path('profile/<str:username>/', views.user_profile, name='user-profile') href in My Template: href="{%url 'user-profile' queryset.username %} I completely messed up. Need help. -
Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name in django
I keep getting this error: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. The following is my code so far: urls.py app_name='stock' urlpatterns = [ path('reset_password/', auth_views.PasswordResetView.as_view(template_name='stock/password_reset.html'), name='reset_password'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name='stock/password_reset_sent.html'), name='password_reset_done'), path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name='stock/password_reset_form.html'), name='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='stock/password_reset_done.html'), name='password_reset_complete'), ] -
Change drop-down labels for Django UserAdmin
I have a User model with a timezone field on it: class User(AbstractBaseUser, PermissionsMixin): timezone = models.CharField( max_length=64, choices=[(tz, tz) for tz in pytz.common_timezones], default="UTC", ) When viewed in Django admin, this creates a drop-down list of timezones, but only of the names. I would like to dynamically generate labels for this drop-down that add the offset as a prefix (e.g. +02:00) and sort the list by that. I know I can create these by doing something like: choices=[ (tz, display_with_offset(tz)) for tz in pytz.common_timezones ], where display_with_offset generates the required label, but I think this would only calculate it when the migrations are run and would ignore any daylight savings changes that happen throughout the year for some regions. My admin file looks like this: class MyUserAdmin(UserAdmin): fieldsets = [ ("Info", {"fields": ("timezone")}), ] admin.site.register(models.User, MyUserAdmin) Is there a way I can dynamically set the drop-down labels? -
Not able to display icons and texts in Bootstrap Navbar
I am trying to display the brand logo followed by a compact disk image along with some text. Problem is the code for displaying icon followed by text works everywhere other than in the tag This is my code. I am using Django in the backend. {% load static %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <link href="https://fonts.googleapis.com/css2?family=Fredoka+One&display=swap" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}"/> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> <nav class="navbar navbar-default"> <div class="container-fluid"> <!--Header--> <a class="navbar-brand" href="{% url 'music:index' %}">JBox</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar"> <span class="navbar-toggler-icon"></span> </button> <!-- Items --> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'music:index' %}"> <i class="fa fa-compact-disk"></i> Albums </a> </li> </ul> </div> </div> </nav> {% if all_albums %} <h3>All Albums:</h3> <ul> {% for album in all_albums %} <li><a href="{% url 'music:detail' album.id %}">{{album.album_title}}</a></li> {% endfor %} </ul> {% else %} <h3>You don't have any albums</h3> {% endif %} -
how to customize django forms
I created a django form using built-in django forms and then assigned variables properly. In front-end, inside html, I customized the form giving my own design instead of built-in forms but did not work. Was trying this for 3 days in a row. Somebody help. How can I make my models, forms and html make insert user data into MySQL db? forms.py: class ProductForm(forms.ModelForm): CHOICES = ( (1,'white'), (2,'silver'), (3,'grey'), (4,'black'), (5,'navy'), (6,'blue'), (7,'sky blue'), (8, 'azure'), (9, 'teal'), (10,'cyan'), (11, 'green'), (12, 'lime'), (13, 'olive'), (14, 'yellow'), (15, 'gold'), (16, 'amber'), (17, 'orange'), (18, 'brown'), (19, 'red'), (20, 'maroon'), (21, 'rose'), (22, 'violet'), (23, 'pink'), (24, 'magenta'), (25, 'purple'), (26, 'indigo'), (27, 'beige'), (28, 'ivory'), (29, 'peach'), (30, 'apricot'), (31, 'ochre'), (32, 'plum') ) CATEGORY = { ('Electronics', ( (1, 'Laptops'), (2, 'Desktops'), (3, 'Smartphones'), (4, 'Smart watches'), (5, 'Circuits'), (6, 'Audio amplifiers'), (7, 'Signal connectors'), (8, 'Audio transducers') )), ('Clothes', ( (9,'Men\'s fashion'), (10, 'Women\'s fashion'), (11, 'Boy\'s fashion'), (12, 'Girl\'s fashion') )), ('Books', ( (13, 'Non-finctions'), (14, 'Fictions'), (15, 'Self-help'), (16, 'Financial'), (17, 'Subjects'), (18, 'Action & Adventure'), (19, 'Classics'), (20, 'Comics'), (21, "Detective & Mystery"), (22, 'Romance') )), ('Beauty & Personal Care', ( (23, 'Makeup'), (24, … -
Django ModelForm. Hide models name
I have a one ModelForm: class First_Form(forms.ModelForm): class Meta: model = Post fields = ('text',) widgets = { 'text': forms.Textarea(attrs={"class": "form-control", "id": "exampleFormControlInput1", "placeholder": "Enter your YouTube link", "rows": 1, }), } On my site it's looking like: Can I hide name of ModelForm field? - "Text"? I want to show only InputField without "Text:" Thank you! -
How to handle a form and formset in the same page?
I have both a form in and a formset for the same model. The first form that I have is written in HTML because I needed some kind of widgets which Django doesn't have out of the box. models.py class MyModel(models.Model): name = models.CharField(max_length=255, null=True, blank=True) phone_number = models.CharField(max_length=255, null=True, blank=True) some_other_field = models.CharField(max_length=255, null=True, blank=True) views.py class MyView(View): def get(self, request): formset = modelformset_factory(MyModel, fields=('name', 'some_other_field', extra=2) return render(request, 'index.html', context={'formset': formset}) def post(self, request): formset = modelformset_factory(MyModel, request.POST, fields=('name', 'some_other_field')) if formset.is_valid(): formset.save() MyModel.objects.create(name=request.POST.get('name')) return HttpResponse("done") index.html <form method="post" action=""> <input type="text" name="name"> {{ formset.management_form }} {% for form in formset %} {{form}} {% endfor %} </form> This does not work at all, cause the request.POST sends all the irrelevant data to the modelformset such as in this case, the name field and I end up with this error. AttributeError: 'QueryDict' object has no attribute '__name__' -
django model form Pointfield returns different value
I’m having trouble with saving PointField using ModelForm, the data returned by cleaned_data attribute is different than what I inserted. anyone has any idea why this is happening, is it because of SRID? data = { 'point_field': (55.980385731737755, 25.39107740672915), 'id': 123 } class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): kwargs['data']['point_field'] = Point(kwargs['data']['point_field']) # Now, kwargs['data']['point_field'].coords returns (55.980385731737755, 25.39107740672915) super(MyForm, self).__init__(*args, **kwargs) form = MyForm(data=data, instance=location_obj) form.is_valid() # returns True form.cleaned_data['point_field'] # returns <Point object at 0x7f363080dc48> form.cleaned_data['point_field'].coords # returns (0.0005028803611372639, 0.00022809192914774866) >>> form.cleaned_data['point_field'].__dict__ {'_constructor_args': (((55.980385731737755, 25.39107740672915),), {}), '_ptr': <django.contrib.gis.geos.libgeos.LP_GEOSGeom_t at 0x7f363080dbf8>, '_cs': <django.contrib.gis.geos.coordseq.GEOSCoordSeq at 0x7f3630817cc0>} >>> form.cleaned_data['point_field'].srid 4326 -
How to display the course topics and topic contents in the same page in python(django)
Let me make my question clear to you guys. I'm developing an educational website where I have to design a course page. In this course page, you'll have all the topics what each course contains. When you click on any topic, its contents should show on the same page. This is my module. [Morever, If I go with a normal procedure, the content page will be displayed on the next page which I don't want. I want this to be dynamic. I want to store all the data into the database as well ] I'm just kind of confused on how to design the database for it however, I've uploaded two pictures here. Please look at them and let me know how this can be achieved. If Ajax needs to be used then let me know how it gonna be. This what I thought table should look like let me know if this can be changed in a proper way- Here is another picture of how the UI should look like. What I want here is when you click on introduction, its content page should display on the same page and in the same manner if I click on the … -
Django - rest_framework_social_oauth2 Proxy server
I have a situation, I have created a project using Django-Rest API with social auth (rest_framework_social_oauth2). In my production architecture application server doesn't have an internet access, which is connected by proxy server and load balancer. The issue is to validate the rest_framework_social_oauth2 by renderer_classes needs internet, please help me how can I apply proxy server settings to verify the rest_framework_social_oauth2 token from facebook and google-oauth2. Thanks in advance -
How to add a linked field in a view from the DetailView class?
There are two models: Document - information about the document, DocVersion - text of the document in a certain edition. Linked via ForeignKey, as one document can have several texts with different revision dates. class Document(models.Model): id = models.AutoField(primary_key=True) doc_title = models.TextField(verbose_name="Name") class DocVersion(models.Model): date_version = models.DateField(verbose_name="Version date") document = models.ForeignKey(Document, on_delete=models.CASCADE) date_start = models.DateField(verbose_name="Start date") text = models.TextField(verbose_name="Text") View based on the DetailView class. class DocumentDetailView(generic.DetailView): model = Document def get_context_data(self, **kwargs): context = super(DocumentDetailView, self).get_context_data(**kwargs) context['text'] = '?????text??????' return context How to fill text with data from the text field of the DocVersion model with the latest date_start? -
Not able to insert data into ArrayField while using psqlextra.backend with django
I have a model with an ArrayField, having JSONField as base. When I try to insert data, it gives the following error: ProgrammingError: column "data" is of type jsonb[] but expression is of type text[] LINE 1: ...e_status_code", "is_success", "error") VALUES (1, ARRAY['"a"... ^ HINT: You will need to rewrite or cast the expression. I am using psqlextra.backend as my default database engine. My model and other relevant codes are: class TestModel(models.Model): data = ArrayField( JSONField(), blank=True, ) My corresponding migration file looks like this: import django.contrib.postgres.fields import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('emails', '0003_auto_20200408_1351'), ] operations = [ migrations.RemoveField( model_name='TestModel', name='data', ), migrations.AddField( model_name='TestModel', name='data', field=django.contrib.postgres.fields.ArrayField(base_field=django.contrib.postgres.fields.jsonb.JSONField(), blank=True, size=None), ), ] I tried adding data like this: TestModel.objects.create( data= [{"a":"b"}, {"c":"d"}] ) -
Django - how to download a file
I am trying to create a download button in my template for a csv file generated by my website (I am new to Django). I have created the view function and updated urls.py but I get 'DoesNotExist: Page matching query does not exist' when I input the url ('http://127.0.0.1:8000/download_table'). I'd also like to know how to create a link/button to the download in my html template. views.py: def download_csv(request): table_selected = request.POST.get('Table_select') index_of_table_selected = int(re.search(r'\d+$', table_selected).group()) result_json_selected = request.session.get('result', 'missing')[index_of_table_selected] dataframe_selected = pd.read_json(result_json_selected) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s' % 'Table.csv' dataframe_selected.to_csv(path_or_buf=response, sep=';', float_format='%.2f', index=False, decimal=",") return response urls.py: urlpatterns = [ path('', views.index, {'pagename': ''}, name='home'), path('<str:pagename>', views.index, name='index'), path('download_table/', views.download_csv, name='download_csv'),] Also, what do I put in my template? Something like this? <a href="download_table/" download> Download File</a> That link returns the error TypeError: download_csv() got an unexpected keyword argument 'filepath' -
Django ORM generated query is not expected
Question desc Execute a query by django orm test_result = table1.objects.filter(q_filter).values(*groupby_columns).annotate(**{d: Sum(d) for d in data_columns}) Got an error Unknown column 'table2.column1' in 'field list' It's strange, because I execute query on model table1 but got an error on model table2 Debug print the sql print(test_result.query) I got this: SELECT `table1`.`column1`, `table1`.`column2`, SUM(`table1`.`data`) AS `data` FROM `table2` WHERE (`table1`.`column3` = 4 AND `table1`.`column4` = 0 AND `table1`.`column1` >= 2020-04-01 AND `table1`.`column1` <= 2020-04-08) GROUP BY `table1`.`column1`, `table1`.`column2` ORDER BY NULL; I'm not sure if there is a cache in django orm, and it record the query clause that I execute last time, so cause this error. It often happen, but recover after I restart my service. Env Python3.6.9 Django2.0.2 Mysql5.6 Does anyone meet this problem. Kindly to talk -
How to reload a view class in Django with different model type?
I'm using a project based approach to learn django by making an e-commerce site. The problem I am having is when I load my index page it shows default item using a class based view. Now what i want is that whenever I click on a category the view should be loaded with products in that category. All other back end is completed i just want to know how implement this in my class based view. Below is a snippet of my view class HomeView(ListView): model = Prod paginate_by = 6 template_name = "index.html" In this case Prod loads all the rows from my table and what i want is that when electronics is clicked on the page only rows containing electronics be shown but by default it should show all product like it does. -
Can't log into localhost:8000/admin ... ERR_CONNECTION_REFUSED
I'm still pretty new to this web dev. I have been having trouble accessing the django admin site. I'm able to do localhost:8000 just fine. If I do localhost:8000/admin, I'm directed to the admin login page. I have already created id/pw through createsuperuser. Anyway, once I type in my id and pw, I noticed my dev server (localhost or 127.0.0.1) terminates and the login page will throw me an error saying "this site can't be reached" with ERR_CONNECTION_REFUSED. I've tried turning off my internet/firewall, but it still gave me the same result. I would greatly appreciate your help. I've been having so much trouble with this because I can't access the django admin site... (i'm using macOS Catalina, if that's any useful. Also I'm just following the basic Django tutorials, so i'm not using anything like gunicorn or nginx either. ) Thanks. -
Get file mime type on pre_save in django admin
I would like to save the file mime type by getting it on pre_save signal. from django.db.models.signals import pre_save from django.db import models import magic class Media (models.Media): file = models.FileField() content_type = models.CharField(max_length=128, editable=False) def media_pre_save(sender, instance, *args, **kwargs): if not instance.content_type: mime = magic.Magic(mime=True) instance.content_type = mime.from_buffer(instance.file.read()) pre_save.connect(media_pre_save, sender=Media) But I'm getting application/x-empty when I view it in db. What am I doing wrong? -
django test giving abnormal results
I am getting weird results when testing for 2 different views. They are both list views. The first one should only show active orders(active=True), the second one only showing historic views (completed=True). I am using postgresql as a database also. Issue is that both the view works perfectly fine in the browser, however when testing pytest raises an error saying that an order that shouldn't be listed, is listed. The views are as follows: class OrderHistoryView(LoginRequiredMixin, ListView): template_name = 'orders/order_history.html' def get_queryset(self): user = self.request.user qs = Order.objects.filter(Q(buyer=user, completed=True)|Q(seller=user, completed=True)) return qs class OrderListView(LoginRequiredMixin, ListView): template_name = 'orders/order_list_view.html' def get_queryset(self): user = self.request.user qs = Order.objects.filter(Q(buyer=user, active=True)|Q(seller=user, active=True)) return qs The tests are: class OrderHistoryViewTests(TestCase): @classmethod def setUp(self): self.req = RequestFactory() self.user = mixer.blend('user.CustomUser', email='test@test.com', password='1234') self.user2 = mixer.blend('user.CustomUser') self.advert = mixer.blend('advert.Advert', author=self.user) self.offer = mixer.blend( 'offer.Offer', advert=self.advert, author=self.user2, receiver=self.user, accepted=True) self.order = mixer.blend( 'orders.Order', advert=self.advert, seller=self.user2, buyer=self.user, offer=self.offer, pending=True, completed=True, active=True, disputed=False, cancelled=False) self.order2 = mixer.blend('orders.Order', completed=False, buyer=self.user) def test_only_shows_completed(self): request = self.req.get('/') request.user = self.user resp = OrderHistoryView.as_view()(request) self.assertContains(resp, self.order) self.assertNotContains(resp, order2) The second test is exactly the same, it just tests that its only showing active orders error message is : FAILED orders/tests/test_views.py::OrderHistoryViewTests::test_only_shows_completed - AssertionError: 3 != … -
Add Mutagen in Django an store result in database?
I'm just started with de Django Framework, and I'm realy new in this. :) I need a thing that print me the duration in seconds of a uploaded mp3 song. So I've found mutagen and this code: # function to convert the seconds into readable format def convert(seconds): hours = seconds // 3600 seconds %= 3600 mins = seconds // 60 seconds %= 60 return hours, mins, seconds # Create an MP3 object # Specify the directory address to the mp3 file as a parameter audio = MP3("G:\Sample.mp3") # Contains all the metadata about the mp3 file audio_info = audio.info length_in_secs = int(audio_info.length) hours, mins, seconds = convert(length_in_secs) print("Hours:", hours) print("Minutes:", mins) print("Seconds:", seconds) Now my stupid question - how can I integrate this in my django (please detailed informations if possible), and how can I store this result (with a button?) in the Django database please? An ansewer would be realy great, thanks in advance. Greetings Frank -
Serving static files from root directory in Django
I have app level static files and want to serve global static files such as JQuery, my project structure is like this: mysite ├───dashboard │ ├───migrations │ ├───static │ │ └───dashboard │ │ ├───css │ │ ├───img │ │ └───js │ └───templates │ └───dashboard ├───etc ├───static │ └───js | └───jquery.min.js └───mysite I added the followed the django docs so that the settings.py looks STATIC_ROOT = "" STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, "static"), os.path.join("static"), ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] when I try to access it from a template, it returns a response code 404 in the runserver log, [09/Apr/2020 01:59:34] "GET /static/js/jquery.min.js HTTP/1.1" 404 1674 the template tag is like this {% load static %} <script src="{% static 'js/jquery.min.js' %}"></script> This is my first django project without following a tutorial, and any help would be appreciated. Thank You -
should the directory of the static file always be myapp/static/myapp/any staticfile
Though i use the staticfiles_dir in the setting and specify where to look for the static files.it works fine and have no problem,or may be there is only one app,so it works nice . i looked into django documentation and it suggests to use both. strong text