Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework social auth
I'm trying to implement the django-rest-framework-social-oauth2 library, following the linked instructions to set up LinkedIn (in place of Facebook). I've added the app, as it says in the instructions, but I don't understand what to do with the redirect URI, as the instructions state that it should be blank. I have a link on my website of the form: https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=CLIEND_ID&redirect_uri= http%3A%2F%2Ffoo.com%2Ffrontend%2Flogin_redirect&scope=r_basicprofile When I click this, linkedin confirms the request and then redirects to the link encoded in the url above (http://foo.com/frontend/login_redirect) with some parameters in the url. I should then send those parameters to a particular linkedin api endpoint to obtain a token for the user. Currently, when linkedin tries to redirect, a 404 error is returned. I tried adding that redirect URI to the redirect URIs of the application, and the result was the same. To summarise, do I need to use a particular redirect url (in which case, what is it?), or, if not, how do I tell django-rest-framework-social-oauth2 which redirect URI it should make available? -
Is it possible to migrate data from MySQL to PostgreSQL through Django dumpdata?
I'm trying to convert my database from MySQL to PostgreSQL, and I'm using AWS RDS. I was trying AWS DMS to migrate data, however it didn't work well and was complicated. While struggling with that, an idea came to mind. What if I use migrate migrations to the new PostgreSQL, and dumpdata from MySQL and loaddata to PostgreSQL? Would that work? Does anyone have experience to migrate database? Am I approaching a right direction? -
Mysqlclient requires MS Visual C++ 10.0 which require again .Net Framework 4
Trying to install with pip install mysqlclient I am installing MysqlClient in Python virtualenv but installation failed with error It requires MS Visual C++ 10.0 I downloaded it, which again requires .NET Framework 4. I again downloaded .NET Framework 4, which is giving error that you cannot install .NET Framework 4 as higher version is already installed. I searched all over the internet there isn't any solution to this problem is available. -
Django Priority Queue
I want to build a delivery app in Django, wherein I will create delivery objects to be delivered according to priority(attribute of the object) by a delivery person. I will login and create the tasks and there can be many delivery persons to login and accept task asynchronously. Objects(tasks) will be popped out as a delivery person logs in and accepts the task, and the next logged in delivery person would see the next priority task. How can this be implemented in Django? Any references and implementation links are welcomed. Thanks in advance! -
Which pattern to use to add functionality to dango models
I have several models in my Django project. Most of these models are quite simple, but some of they are the entry point to complex data structures. For example, Reservation model has several detail models through foreign key relationships (ReservationHotel, ReservationTransfer, ReservationTour, ReservationRountrip, ReservationService), and each one of these details has foreign relationship with product models (Hotel, Transfer, Tour, Roundtrip, Services). I know a good practice is to keep models isolated from other models, so they must not know the detail about them. Due to this, I implement controllers to manage complex data structures like the one described before. I want these controller to implement design patterns, and I believe the proper one for Reservations should be the Proxy pattern, based in its description in wikipedia: What problems can the Proxy design pattern solve? The access to an object should be controlled . Additional functionality should be provided when accessing an object. When accessing sensitive objects, for example, it should be possible to check that clients have the needed access rights. What solution does the Proxy design pattern describe? Define a separate Proxy object that can be used as substitute for another object (Subject) and implements additional functionality to control … -
Django REST: How to overwrite field type of a serializer class
I am trying to overwrite serializer's data field, which is a CharField,like this: from jsonfield import JSONField class ActivitySerializer(serializers.ModelSerializer): data = JSONField() class Meta: model = Activity fields = ("date_added", "start_date", "data", "number", "athlete") But when I try to print the representation of the serializer -print(repr(my_serializer)) - the type of field data remains unchanged: ActivitySerializer(<Activity: START DATE: 2018-11-19 06:08:49+00:00, ID: 1973222369, DATE ADDED: 2018-11-20 18:07:32.818798+00:00>): date_added = DateTimeField(read_only=True) start_date = DateTimeField(required=False) data = CharField(style={'base_template': 'textarea.html'}) number = IntegerField(required=False) athlete = PrimaryKeyRelatedField(queryset=Athlete.objects.all(), required=False) What am I doing wrong? -
Unique=True in Django model gives IntergretyError instead of ValidationError
I want to show a validation message like "This email is already in use" inside my html form. But I think i'm missing something. I keep getting an IntegrityError at my email field. Isn't Django supposed to validate this and give an ValidationError if I use unique=True in my model? Or do I have to Try and Catch the IntegrityError myself? Or maybe show me a best practice for validating unique users inside a form/model. models.py class Customer(models.Model): FirstName = models.CharField(max_length=50) LastName = models.CharField(max_length=50) Email = models.CharField(max_length=50, unique=True, error_messages={'unique':"This email is already in use"}) views.py def customerform(request): if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): post = Customer() post.FirstName = form.cleaned_data['FirstName'] post.LastName = form.cleaned_data['LastName'] post.Email = form.cleaned_data['Email'] post.save() return render(request, 'results.html', { 'FirstName': form.cleaned_data['FirstName'], 'Email': form.cleaned_data['Email'],}) else: form = CustomerForm() return render(request, 'form.html', {'form':form}) forms.py class CustomerForm(forms.Form): FirstName = forms.CharField (label='First name:', max_length=50) LastName = forms.CharField (label='Last name:', max_length=50) Email = forms.EmailField(label='Email:', max_length=50) form.html <form action="/customer/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> -
Django Queryset Batches
I have a Django app that runs on SQL Server. SQL Server allows a maximum of 2,100 parameters in a user-defined function. I have a Django view that is attempting to return 10,000 results: def result_list(request): results = MyModel.objects.filter(~(Q(importantField='') | Q(importantField='Some Text'))).select_related('field','field2','field3','field4').prefetch_related('anotherField') return render(request, 'results/result_list.html', {'results':results}) Error: Request Method: GET Request URL: https://server/results/result_list Django Version: 1.11.3 Python Version: 3.6.3 Traceback: File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\db\backends\utils.py" in execute 65. return self.cursor.execute(sql, params) File "D:\Python\Anaconda3\envs\django\lib\site-packages\sql_server\pyodbc\base.py" in execute 545. return self.cursor.execute(sql, params) The above exception (('07002', '[07002] [Microsoft][SQL Server Native Client 11.0]COUNT field incorrect or syntax error (0) (SQLExecDirectW)')) was the direct cause of the following exception: File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "D:\Websites\project\app\views.py" in result_list 476. return render(request, 'results/result_list.html', {'results':results}) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\template\loader.py" in render_to_string 68. return template.render(context, request) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\template\base.py" in render 207. return self._render(context) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\test\utils.py" in instrumented_test_render 107. return self.nodelist.render(context) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "D:\Python\Anaconda3\envs\django\lib\site-packages\django\template\base.py" in render_annotated 957. return … -
Django - TemplateDoesNotExist at /password_reset
I have a django app, that is using the django.contrib.auth package for user authentication. I'm trying to add password reset functionality using the auth views provided by the package. However, I'm getting an error when i actually navigate to that url (ttp://localhost:8000/password_reset). Does anyone have an idea on what the issue could be Error Current urls.py (i don't think a view is needed if done right) from django.urls import path, include from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('profile/<username>', views.profile, name='profile'), path('register', views.register, name='register'), path('login', views.login_view, name='login'), path('password_reset', auth_views.PasswordResetView.as_view(), name='password_reset'), # path('password_reset', auth_views.PasswordResetView.as_view(template_name='accounts/password_reset_done.html'), name='password_reset'), path('password_reset_done', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password_reset_confirm', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('password_reset_complete', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), path('purchase', views.purchase, name='purchase'), ] settings.py INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'avatar', ] Similar post, but did not reslove TypeError at /password_reset/ django Documentation https://docs.djangoproject.com/en/2.1/topics/auth/default/ -
Django py manage.py makemigrate
enter image description here What can I make with it? I'm beginner in python and django. I download it and I i wrote py manage.py makemigrate and I've get error. Can u help me? -
Django dumpdata returns empty array when models are in a version subdirectory
I have a Django Rest Framework app where I have separated my models/serializers/views into separate directories (instead of in models.py, serializers.py, etc) and moved those directories into a v1 directory. When I try to run ./manage.py dumpdata api I get an empty array as response. ./manage.py dumpdata will dump out the Django system tables, but none of my model tables. Here's an example: - api/ -- __init__.py -- v1/ --- router.py --- __init__.py --- models/ ---- __init__.py ---- thingy.py --- serializers/ ---- __init__.py ---- thingy.py --- views/ ---- __init__.py ---- thingy.py - project/ -- urls.py -- settings.py -- wsgi.py -- __init__.py The __init__.py file inside each object directory (e.g. models) includes the class from each file: from .thingy import Thingy The router.py file inside api/ looks like this: from rest_framework import routers from . import views router = routers.DefaultRouter(trailing_slash=False) router.register(r'thingies', views.ThingyViewSet) api_urlpatterns = router.urls And urls.py inside project/ looks like this: from django.conf.urls import url, include from django.contrib import admin from django.urls import path from api.v1.router import api_urlpatterns as api_v1 urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/v1/', include(api_v1)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] -
Django, JavaScript, Google Street View: Linking JavaScript 'Click' Event Listeners for Multiple Items to Django Product & Cart Model
I would like to implement in Django a Google Street View where I could use JavaScript event listeners - 'click' to determine if buttons (Add to Cart) in the Street View has been clicked, so that all the items clicked on in the Google Street View is added to a cart when it is clicked.[reference here][1] In a typical Django shopping website, the products is added via the Django admin into the models. Then at the Django templates, the products are run iteratively with a 'for' loop to show all available products. Similarly for the cart to show all added products. {% for product in products.object_list %} {% for cart_item in cart_items %} I plan to add all products into the Django models first. The problem is how can I link every button (Add to Cart) for each specific product item in Google Street View via JavaScript 'Click' event listeners to the Django models/views? Is there a short code example that can show this being done? Thank you! -
How can I add data to my model containing User as a foreign key from a custom-made form in django?
Here, when I try to add a new note with a user logged in, I want that note to have its user-field filled with the current logged in user. So I wrote user=request.user But error arises: UNIQUE constraint failed: mynotes_note.user_id Here are my files: models.py class Note(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=50) desc = models.TextField() def __str__(self): return self.title addForm.py from django import forms class addForm(forms.Form): title = forms.CharField(max_length=50, widget=forms.TextInput(attrs={ 'class':'form-control' })) desc = forms.CharField(widget=forms.TextInput(attrs={ 'class':'form-control' })) Here, I used this way instead of using Meta class just to apply some bootstrap effects to the form fields views.py def addView(request): if request.user.is_active: if request.method=="POST": form=addForm(request.POST) if form.is_valid(): newNote = Note(user=request.user,title=request.POST['title'],desc=request.POST['desc']) newNote.save() return redirect('home') else: form=addForm() args={'form':form} return render(request,'mynotes/add.html',args) else: return redirect('home') -
Map visualization/popup with Django and Leaflet
I am new to Django and I am struggling with a problem for many weeks. My template/html page works fine with leaflet, but when I run the template on Django it doesnt load my map (geoJson file). I have tried watching all the tutorials but no luck. Could anyone please help? I have uploaded a picture which comes alright using only leaflet and html, but comes blank on Django server. Below is my code: [![<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <meta name="viewport" content = "width=device-width,initial-scale=1"/> <title> Map Visualization </title> <!-- Leaflet --> <link rel= "stylesheet" href="../../leaflet/leaflet.css"/> <script src = "../../leaflet/leaflet.js"></script> <script src ="../data/countries.geojson"></script> <style type = "text/css"> #map { height : 800px; width: 70%; align: left } #filter { height:800px; width: 20% align: right } </style> </head> <body> <h1 style="color:green;"> Map Visualization </h1> <div id="map"></div> <script> function getStateColor(stateShade){ if (stateShade =="colored-state"){ return '#6666ff'; }else if(stateShade!="non-colored-state"){ return '#D3D3D3'; } } function countriesStyle(feature){ return { fillColor : getStateColor(feature.properties.shade), weight : 2, opacity : 1, color: 'white', dashArray : 2.5, fillOpacity :0.7 } } var map = L.map('map').setView(\[80, 30\], 19) var countriesLayer = L.geoJson( countries, {style : countriesStyle} ).addTo(map); map.fitBounds(countriesLayer.getBounds()); var point1 =\[44.066803,-93.533061\]; var point2 = \[43.064,-89.5347\]; var marker1 = L.marker(point1).addTo(map).bindPopup("<p>State: MN" ); … -
Intermittent IndexError with MySQL and Django running on Ubuntu
Here is what I'm getting: Traceback (most recent call last): File "/.../.env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/.../.env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/.../.env/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 20, in _wrapped_view if test_func(request.user): File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 44, in <lambda> lambda u: u.is_authenticated, File "/.../.env/lib/python3.6/site-packages/django/utils/functional.py", line 213, in inner self._setup() File "/.../.env/lib/python3.6/site-packages/django/utils/functional.py", line 347, in _setup self._wrapped = self._setupfunc() File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/middleware.py", line 24, in <lambda> request.user = SimpleLazyObject(lambda: get_user(request)) File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/middleware.py", line 12, in get_user request._cached_user = auth.get_user(request) File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 189, in get_user user = backend.get_user(user_id) File "/.../.env/lib/python3.6/site-packages/django/contrib/auth/backends.py", line 98, in get_user user = UserModel._default_manager.get(pk=user_id) File "/.../.env/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/.../.env/lib/python3.6/site-packages/django/db/models/query.py", line 393, in get num = len(clone) File "/.../.env/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __len__ self._fetch_all() File "/.../.env/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/.../.env/lib/python3.6/site-packages/django/db/models/query.py", line 63, in __iter__ for row in compiler.results_iter(results): File "/.../.env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1007, in apply_converters value = row[pos] IndexError: list index out of range As you can see, there is none of my code in the stacktrace, all I know is that this code is happening somewhere in a very simple view that gets … -
how can i show active page in Django pagination
am using django 2.0 and am trying to make this blog, the issue is that once i click the next page the active bar in the pagination section dont change mean from 1 to 2 see pic image i don't know where is the mistake here is the views.py def post_list(request): object_list=Post.objects.filter(status='Published').order_by("-created") pages = pagination(request,object_list,3) context={ 'items':pages[0], 'page_range':pages[1], } return render(request,"blog.html",context) pagination function from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator def pagination(request,data,num=10): paginator = Paginator(data,num) # Show 5 contacts per page page = request.GET.get('page',5) try: items=paginator.page(page) except PageNotAnInteger: items=paginator.page(5) except EmptyPage: items=paginator.page(paginator.num_pages) index=items.number=1 max_index=len(paginator.page_range) start_index=index - 5 if index >= 5 else 0 end_index=index + 5 if index <= max_index - 5 else max_index page_range=paginator.page_range[start_index:end_index] return items, page_range and pagination.html <nav> {% if items.has_other_pages %} <ul class="pagination"> {% if items.has_previous %} <li><a href="?page={{ items.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in page_range %} {% if items.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if items.has_next %} <li><a href="?page={{ items.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> </ul> {% endif %} {% endif %} </nav> blog.html {% for obj … -
Wagtail: Getting a list of snippets with counts of related parents
Using Wagtail I have ArticlePages, each of which can have 0 or more Authors, which are Snippets. I'd like to get a list of Authors with the number of ArticlePages they're attached to, but can't work out how. I'm getting confused by ModelCluster I think, as I'd be fine with vanilla Django. (I'm not even sure if I'm over-complicating this; I don't need the Authors to be orderable on the Articles...) from django.db import models from modelcluster.fields import ParentalKey from wagtail.admin.edit_handlers import InlinePanel from wagtail.core.models import Orderable, Page from wagtail.snippets.edit_handlers import SnippetChooserPanel from wagtail.snippets.models import register_snippet class ArticlePage(Page): content_panels = Page.content_panels + [ InlinePanel('authors', label='Authors'), ] @register_snippet class Author(models.Model): name = models.CharField(max_length=255, blank=False) panels = [ FieldPanel('name'), ] class ArticleAuthorRelationship(Orderable, models.Model): author = models.ForeignKey( 'Author', on_delete=models.CASCADE, related_name='+') page = ParentalKey( 'ArticlePage', on_delete=models.CASCADE, related_name='authors') panels = [ SnippetChooserPanel('author'), ] FWIW, I know I could get a single Author's articles using article.get_usage(), which is handy! -
How to add more than one django-leaflet map in a view?
I was able to show a map on a single page using django-leaflet. In another page, I am trying to show two (or more) maps in page but I couldn't figure out how. For showing map in a single page: <div class="card"> {% leaflet_map "main" callback="map_init" %} </div> <script type="text/javascript"> function map_init(map, options) { // get point lat and lon var lon = "{{ project.longitude }}"; var lat = "{{ project.latitude }}"; // zoom to point & add it to map map.setView([lat, lon], 12); L.marker([lat, lon]).addTo(map); }</script> Above works fine as long as one map needs to be shown. However I am not sure how I can modify above to support multiple maps. I have started jsfiddle page here (which is kind of blank), not sure if it's going to helpful. What I am trying is to fill the 'img-top' div in the html below: var locations = [ {"lat":27.988098,"lng":86.924925}, {"lat":27.679535,"lng":83.507020} ] <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="card-columns m-5"> <div class="card"> <div class="card-header">Location A </div> <div class="img-top" id="map-1" style="height:200px"></div> <div class="card-body"> Some information of A </div> </div> <div class="card"> <div class="card-header">Location B </div> <div class="img-top" id="map-2" style="height:200px"></div> <div class="card-body"> Some information of B </div> </div> </div> -
No 'Access-Control-Allow-Origin' header is present on the requested resource error in fetch API django
I'm trying to fetch some data from an API. It works and my data is send to the server but I am getting the following error message that unable me to continue: Access to fetch at 'http://192.168.80.11:8000/upload/5bc4206e3ff2286d24c58899/' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I know that this is because I am trying to fetch that data from within my localhost and the solution should be using CORS. But how can I set Access-Control-Allow-Origin in the response header? I use Django. And this is setting file on server: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGINE_ALLOW_ALL= True CORS_ALLOW_CREDENTIALS = True #CORS_ORIGINE_ALLOW_ALL= False CORS_ORIGINE_WHITELIST=( 'http//:192.168.20.29:8000', 'http//:192.168.20.30:8000', 'http//:127.0.0.1:8000', ) -
Should I use JSONField over ForeignKey to store data?
I'm facing a dilemma, I'm creating a new product and I would not like to mess up the way I organize my datas in my database from the start. I have two choices to organize my models, the first one would be to use foreign keys to link my models together. Class Page(models.Model): data = JsonField() Class Image(models.Model): page = models.ForeignKey(Page) data = JsonField() Class Video(models.Model): page = models.ForeignKey(Page) data = JsonField() etc... The second one is to keep everything in Page: Class Page(models.Model): data = JsonField() # videos and pictures, etc... are stored here Is one better than the other and why? This would be a huge help on the way I would organize my databases in the futur. -
Django 1.6.5 user registration error no such table: auth_user
my settings.py: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'Mysite' ) AUTH_USER_MODEL = 'Mysite.PortalUserAbstract' my Mysite.models.py: class PortalUserAbstract(AbstractUser): is_client = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) error message : OperationalError at /accounts/signup/client/ no such table: auth_user Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/client/ Django Version: 1.6.5 Exception Type: OperationalError Exception Value: no such table: auth_user when i do manage.py syncdb it creates table "Mysite_portaluserabstract" but the auth module still looks for auth_user table. what am I missing? -
i am getting an error when running django
Unhandled exception in thread started by .wrapper at 0x038C1C48> this is what i get when trying to run an app that was created earlier on a different machine, when i create a new project it runs just fine but everytime i try to run the app that had been created before it throws the error listed here in above, please assist. this is the whole CMD dump: C:\Users\Gavina\Desktop\kesh\lawcases>python manage.py migrate Traceback (most recent call last): File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\logging\config.py", line 562, in configure handler = self.configure_handler(handlers[name]) File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\logging\config.py", line 735, in configure_handler result = factory(**kwargs) File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\logging__init__.py", line 1092, in init StreamHandler.init(self, self._open()) File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\logging__init__.py", line 1121, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) FileNotFoundError: [Errno 2] No such file or directory: 'C:\opt\django-cases\logs\debug.log' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.3-py3.7.egg\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.3-py3.7.egg\django\core\management__init__.py", line 357, in execute django.setup() File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.3-py3.7.egg\django__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.3-py3.7.egg\django\utils\log.py", line 76, in configure_logging logging_config_func(logging_settings) File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\logging\config.py", line 799, in dictConfig dictConfigClass(config).configure() File "C:\Users\Gavina\AppData\Local\Programs\Python\Python37-32\lib\logging\config.py", line 570, in configure '%r' % name) from e ValueError: Unable to configure handler 'file' Thank you for your assistance -
Django cant translate captcha label
I'm using django-recaptcha and django-contact form. My contact form showing like this and working perfectly; It translates on all other titles except "Captcha". I could not find the word "Captcha" anywhere. i search this "Captcha" word all in my project but i cant find... No in my lang folder, no models or forms py How can i translate this label? where does this word come from? my contactform forms.py """ A base contact form for allowing users to send email messages through a web interface. """ from django import forms from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.utils.translation import gettext_lazy as _ from django.core.mail import send_mail from django.template import loader class ContactForm(forms.Form): """ The base contact form class from which all contact form classes should inherit. """ name = forms.CharField(max_length=100, label=_('Your name')) email = forms.EmailField(max_length=200, label=_('Your email address')) title = forms.CharField(max_length=200, label=_('Subject')) body = forms.CharField(widget=forms.Textarea, label=_('Your message')) from_email = settings.DEFAULT_FROM_EMAIL recipient_list = [mail_tuple[1] for mail_tuple in settings.MANAGERS] subject_template_name = "contact_form/contact_form_subject.txt" template_name = 'contact_form/contact_form.txt' def __init__(self, data=None, files=None, request=None, recipient_list=None, *args, **kwargs): if request is None: raise TypeError("Keyword argument 'request' must be supplied") self.request = request if recipient_list is not None: self.recipient_list = recipient_list super(ContactForm, self).__init__(data=data, files=files, *args, **kwargs) … -
Django How To Query ManyToMany Relationship Where All Objects Match
I have the following models: ## Tags for issues class issueTags(models.Model): name = models.CharField(max_length=400) class issues(models.Model): tags = models.ManyToManyField(issueTags,blank = True) In my view I get an array from some client side JavaScript i.e. (Pdb) array_data = request.POST['arr'] (Pdb) array_data '["2","3"]' How should I filter my issues object to find all issues which match all tags in the array? (the 2,3 are the ID values for tag__id. If there is a better way to arrange the objects that would also work so I can search in this fashion. -
Django - modeling - multi-table reference
SOS - HELP : I am newbie in django ( I came from PHP (Laravel)): I need modeling the data : I have same models they are named Sources like(IOT, Sensosr, Totens, app etc..) each source has your particularity(conection params) and similarity, then I have scans, scans use sources information to execute (store information about execution) and produce activities on hosts. I need to link activities to sources through scans, so that, when a activity is showed, information about hosts, scans, and source are showed. I learning about abstract but it not so clear !