Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No module named django
When running: (DjangoProject) PS C:\Users\Travinns\Documents\GitHub\HBH site> django-admin.py startproject HBHsite I get the error: from django.core import management ModuleNotFoundError: No module named 'django' I followed this guide and it goes wrong at the 'Lets now create a our first Django project.' step. I already searched around and if I run the following: python -c "import sys; print('\n'.join(sys.path))" I get: C:\Users\Travinns\Envs\DjangoProject\Scripts\python35.zip C:\Users\Travinns\Envs\DjangoProject\DLLs C:\Users\Travinns\Envs\DjangoProject\lib C:\Users\Travinns\Envs\DjangoProject\Scripts c:\users\travinns\appdata\local\programs\python\python35-32\Lib c:\users\travinns\appdata\local\programs\python\python35-32\DLLs C:\Users\Travinns\Envs\DjangoProject C:\Users\Travinns\Envs\DjangoProject\lib\site-packages C:\Users\Travinns\Documents\GitHub\HBH site Django is in C:\Users\Travinns\Envs\DjangoProject\lib\site-packages so this should work. If I run: Python import django django I get: <module 'django' from 'C:\\Users\\Travinns\\Envs\\DjangoProject\\lib\\site-packages\\django\\__init__.py'> Which confirms my statement. What am I missing? Extra info: I am running on Windows. -
django rest framework: customize nested serializer
I have the following Django model structure: class TypeOfIngredient(models.Model): name = models.CharField(max_length=200,unique=True,null=False) slug = models.SlugField(unique=True) class Ingredient(models.Model): name = models.CharField(max_length=200,unique=True,null=False) slug = models.SlugField(unique=True) typeofingredient = models.ForeignKey(TypeOfIngredient, related_name='typeof_ingredient',null=True, blank=True,on_delete=models.PROTECT) Serializer: class IngredientListSerializer(ModelSerializer): class Meta: model = Ingredient fields = '__all__' With the above serializer i see the following api output: "results": [ { "id": 1, "name": "adrak", "slug": "adrak", "typeofingredient": null }, { "id": 2, "name": "banana", "slug": "banana", "typeofingredient": 1 }, How to get "typeofingredient": "fruit" where fruit is the name field of the typeofingredient. What i am getting is the id. I tried nested: class IngredientListSerializer(ModelSerializer): class Meta: model = Ingredient fields = '__all__' depth = 1 Then i get the api output as: "results": [ { "id": 1, "name": "adrak", "slug": "adrak", "typeofingredient": null }, { "id": 2, "name": "banana", "slug": "banana", "typeofingredient": { "id": 1, "name": "fruit", "slug": "fruit" } }, Here is showing all the details of the typeofingredient. Rather than this can i have directly "typeofingredient": "fruit" -
How to GET data by search word Django
I have problem getting the data to the home page. I would like to filter out all the books based on Genre. I'm following the MDN site for this. index.html {% extends "base_generic.html" %} {% block content %} <h1>Local Library Home</h1> <p>Welcome to <em>Local Library</em>, a very basic Django website.</p> <h2>Dynamic content</h2> <form action="" method="get"> <input type="text" name="genre" placeholder="Search"> <input type="submit" value="Search"> </form> {% endblock %} urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^books/$', views.BookListView.as_view(), name='books'), url(r'^(?P<string>[-\w]+)$', views.GenreListView.as_view(), name='index'), ] GenreListView class class GenreListView(generic.ListView): model = Book def get(request, string): try: book = Book.objects.all().filter(genre=string) except Book.DoesNotExist: raise Http404("Book does not exist") return render( request, 'index.html', context={'book': book,} ) I can't figure out what I'm missing or what else I have to do to get all the date based on genre? -
3-legged authorization for twitter in django
I try to make a 3-legged authorization in django with twitter, but my code doesn't work. I get an error massage that says "invalid oauth_verifier parameter" Does anyone have an idea of what I am doing wrong? I think there is something wrong with: resp, content = client.request(access_token_url, "POST") but I don't know what. In my view.py: def settings(request): consumer_key = "xxx" consumer_secret = "xxx" request_token_url = 'https://api.twitter.com/oauth/request_token' access_token_url = 'https://api.twitter.com/oauth/access_token' authorize_url = 'https://api.twitter.com/oauth/authorize' consumer = oauth.Consumer(consumer_key, consumer_secret) client = oauth.Client(consumer) resp, content = client.request(request_token_url, "GET") request_token = dict(cgi.parse_qsl(content)) url_name = "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token']) form = forms.PinForm() user = request.user if request.method == 'POST': form_value = forms.PinForm(request.POST) oauth_verifier = form_value['pin'].value().strip() token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(oauth_verifier) client = oauth.Client(consumer, token) resp, content = client.request(access_token_url, "POST") access_token = dict(cgi.parse_qsl(content)) print "Access Token:" print access_token return HttpResponseRedirect("/") return render(request, 'test/settings.html' , {'form': form, 'url_name': url_name}) in my settings.html: {% include "test/head.html" %} <div class="container"> <br> </div> <div> <a href="{{ url_name }}" target="_blank">Get Pin from Twitter</a> <br><br> <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Send Pin" name='Pin'> </form> </div> -
How to deploy django with media files?
I am trying to find a simple solution to deploy a django rest api which uses media files which are added via the admin panel. The rest api will be receiving very low traffic and so the simplest cheapest option is preferable. Currently, I am using heroku, however when I add media files through the admin panel and come back to it later the files are no longer there. Here is my settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '****' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['example.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'clothing', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', ], 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '400/day', 'user': '500/day' } } ROOT_URLCONF = 'good_deal.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, … -
Django CreateView - Display only particular objects in foreignkey field
I have a CreateView view that has a bunch of fields that need to be filled by the user when creating a new contact. Now, I want the user to be able to see and choose only from the categories that they'd created. This is the model of Category: class Category(models.Model): class Meta: verbose_name = _('category') verbose_name_plural = _('categories') name = models.CharField(max_length=100, unique=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) def __unicode__(self): return self.name This is the view: class ContactCreate(LoginRequiredMixin, generic.edit.CreateView): model = models.Contact success_url = reverse_lazy('site:contacts') fields = ['firstname', 'lastname', 'phone1', 'phone2', 'email', 'city', 'category'] template_name = 'site/contacts.html' context_object_name = 'all_contacts' What I need the user to see is a select that has only the categories which include the appropriat profile foreignkey associated with them. I'd be glad to get some help with this. Thank you! -
can't started server for django i'm new in django and interpreter is pycharm
can't start my server for django project i'm using pycharm and faced several issues . further in pictureterminal with commands -
How to relate two object lists?
I have two models related them with a foreign key, pregunta is a question to a especific Comentario (comment). models.py class Comentario (models.Model): titulo = models.CharField(max_length=50) texto = models.CharField(max_length=200) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) fecha_publicacion = models.DateTimeField(auto_now_add=True) tag = models.ManyToManyField(Tags, blank=True) def __str__(self): return (self.titulo) class Pregunta (models.Model): descripcion = models.CharField(max_length=150) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) fecha_pregunta = models.DateTimeField(auto_now_add=True) comentario_preguntado = models.ForeignKey(Comentario, null=True, blank=True) def __str__(self): return (self.descripcion) I create a view where I want to show only the comments having a question and the questions itself. I create two object list, one with the comments and the other with questions. The problem is that I want to show in the template the first comment and its questions, then the next comment and its questions... I do not know if this should be done in the template or I need to change my view. views.py def responder(request): comment = Comentario.objects.filter(id__in=Pregunta.objects.all().values_list('comentario_preguntado')).filter(autor=request.user) question = Pregunta.objects.filter(comentario_preguntado__in=comment) return render(request, 'home/responder.html', {'comment': comment, 'question': question}) -
How to get inline model in post_save instance (Django Signals)?
I'm using Django (1.11.7) and Signals for some actions on the newly saved model (sending a message to the mail with the info from the model, basically). But only I add to this model one more, connected (ForeignKey) with the main (as inlines=[...] in admin.py) — it does not participate in saving the instance of the main model. My model is: # /tours/models.py class Tours(models.Model): country = models.CharField(...) ... class ToursHotels(models.Model): tour = models.ForeignKey(Tours, ...) cost = models.IntegerField(...) ... @receiver(post_save, sender=Tours) def do_something(sender, **kwargs): tour = Tours.objects.get(id=kwargs.get('instance').id) hotels = ToursHotels.objects.filter(tour_id=tour.id).order_by('cost') ... So, hotels will be empty until I edit this record again. How to do it better? Help me please. -
Reading published python code
I am learning python and django and my friend from school told me I should be worried about obfuscating my project I'm about to deploy.. Is it possible to read published django code? Specifically my views? If so, how? -
Django REST framework: HTML render Generic APIView
I am new to Django REST Framework. What I try to do is to render a Generic APIView (RetrieveUpdateDestroyAPIView) in HTML similarly to the way the ViewSet is automatically rendered in the Browsable API. Following the official documentation, I have in my myApp/views.py: class AnnounceViewSet(viewsets.ModelViewSet): """ API endpoint that allows announces to be viewed or edited. """ queryset = Announce.objects.all() serializer_class = AnnounceSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def perform_create(self, serializer): # without this, the POST request of the announce doesnt work serializer.save(owner=self.request.user) class AnnounceList(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'myApp/announces_list.html' permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def get(self, request): queryset = Announce.objects.all() return Response({'announces': queryset}) class AnnounceDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Announce.objects.all() serializer_class = AnnounceSerializer renderer_classes = [TemplateHTMLRenderer] template_name = 'myApp/announce_detail.html' permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) In my urls.py: from django.conf.urls import url, include from rest_framework import routers from myApp import views from django.contrib import admin router = routers.DefaultRouter() router.register(r'api/users', views.UserViewSet) router.register(r'api/groups', views.GroupViewSet) router.register(r'api/announces', views.AnnounceViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('myApp.urls')), url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^accounts/', include('allauth.urls')), url(r'^announces/$', views.AnnounceList.as_view(), name='announces-list'), url(r'^announces/(?P<pk>[0-9]+)/$', views.AnnounceDetail.as_view(), name='announce-detail'), When I go the Brwowsable API, through the link /api/announces/3/, I can … -
Testing with Pytest and Hypothesis
I'm required to run tests that use hypothesis as the testing strategy but I'm having problem including it in my test so I need some help. def to_svg(filename): filename='profile' SVG_DIRS = getattr(settings, 'SVG_DIRS', []) path = None if SVG_DIRS: for directory in SVG_DIRS: svg_path = os.path.join(directory, '%s.svg' % filename) if os.path.isfile(svg_path): path = svg_path else: path='/home/user/Desktop/Scripts/django1_11/myapp/'+str(filename)+'.svg' if isinstance(path, (list, tuple)): path = path[0] with open(path) as svg_file: svg = mark_safe(svg_file.read()) return svg So that's some of the code that I'm supposed to write tests for. How would I do that ? I have to open a specific file called profile.svg and return it in my function so that it loads on my webpage but hypothesis gives random strings and I need to have a specific one to open this file. I know that hypothesis isnt the way to do this but I'm required to use it. Thanks in advance. -
django way to redirect on timeout
I want to understand if the approach I've used to redirect to another page on timeout is a proper one, or if there is a more adequate way in Django. This is my template: {% extends "base.html" %} {% block content %} <h1>Thanks for visiting, come back soon!</h1> <script type="text/javascript"> setTimeout(function() { window.location.href = '/home/'; }, 2000); </script> {% endblock %} This is my urls.py: url(r"^$", views.HomePage.as_view(), name="home"), url(r"^home/$", views.HomePage.as_view()), Would it be possible to combine the two lines in one? (I'm thinking of the "Don't repeat yourself" principle) -
Get all input values into a list javascript
When the response page renders, it renders various input fields. I am trying to get this into a list which, using ajax will be sent back to the django view. here is the html and javascript i am trying to use to achieve this. <div id ='answers'> {% for q in questions %} {{q.question.numeric}} {% if q.question.numeric%} <div class = 'numeric_answer'> {{ q.question.question_text }}<br> <select name="Score"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> {% else %} <div class = 'text_answer'> {{ q.question.question_text }}<br> <input type="text" class="question_text"/><br> </div> {% endif %} {% endfor %} </div> <button id="send">Submit</button> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var button = $("#send"); $(button).click(function() { var vals = []; $("#answers :input").each(function(index) { vals.push(this.val); }); vals = JSON.stringify(vals); console.log(vals); }); }); </script> Currently, no matter what is entered, I get a list which just contains 'nulls' eg [null, null, null] when I want a list like ['hey', 'asdasd', 5, 'ásdas'] -
Django error: Reverse for 'password_reset_confirm' with no arguments not found
I am using Django 1.11 to build an user account application. My urls for my account app is as Code 1 as below. And also I have a templates/registrations folder and several template files there: enter image description here After I input the email address and I receive the email with the following link: http://127.0.0.1:8000/account/password-reset/confirm/MQ/4ra-66d3672f1d340589fbf9/ I click the above link and the browser redirects to this link: http://127.0.0.1:8000/account/password-reset/confirm/MQ/set-password/ And the error prompts: NoReverseMatch at /account/password-reset/confirm/MQ/set-password/ Reverse for 'password_reset_confirm' with no arguments not found. 1 pattern(s) tried: ['account/password-reset/confirm/(?P[-\w]+)/(?P[-\w]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/account/password-reset/confirm/MQ/set-password/ Django Version: 1.11.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'password_reset_confirm' with no arguments not found. 1 pattern(s) tried: ['account/password-reset/confirm/(?P[-\w]+)/(?P[-\w]+)/$'] Please help me how to solve this problem. It seems that after I click the link, the Django fails to render the password_reset_confirm.html under templates/registration folder. Code 1: # restore password urls url(r'^password-reset/$', auth_views.PasswordResetView.as_view(), name='password_reset'), url(r'^password-reset/done/$', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), url(r'^password-reset/confirm/(?P<uidb64>[-\w]+)/(?P<token>[-\w]+)/$', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url(r'^password-reset/complete/$', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), -
Django post method returns only blank values for checkboxes
I have tried to look around for this specific query on SO, but could not find one. I am new to Django and am using version 1.10 and python 3.4. For the checkboxes I am using them in the template itself. For some reason I am hesitant in using the checkbox widget in the forms.py file, I think it will disturb my existing UI(please correct me if I am wrong). When I submit the form, the template returns blank quotes for the number of checkboxes I have ticked. Here is my model: class UsrGrpMaster(models.Model): SrNo =models.IntegerField(unique=True) UsrGrpID = models.AutoField(primary_key=True) GrpName = models.CharField(max_length=50) Purch = models.BooleanField(default=False) PurchMod = models.BooleanField(default=False) Sales = models.BooleanField(default=False) SalesMod = models.BooleanField(default=False) Stock = models.BooleanField(default=False) StockMod = models.BooleanField(default=False) JV = models.BooleanField(default=False) JVMod = models.BooleanField(default=False) DelPurch = models.BooleanField(default=False) DelSales = models.BooleanField(default=False) DelJV = models.BooleanField(default=False) class Meta: db_table = "UsrGrpMaster" Here is my template: <div class="body-set"> <div id="form"> <form class="form-horizontal" method="POST" action="{% url 'creategroup' %}"> <div class="form-group" align="center"> <label class=""><font size="6">Create a New User Group</font></label>{% if errormsg %}<br /> <font size="3" color="#FF0000">{{ errormsg }}</font>{% endif %} </div> <div class="form-group"> <label class="control-label col-sm-4" for="text">Name of the User Group:</label> <div class="col-sm-5"> <input type="text" class="form-control" id="grpname" placeholder="Type in the new User Group Name" … -
uWsgi does not see django as www-data user
When I start uWsgi as me (uid=<my_username>) everything works. However, if I do it as www-data user to link uwsgi with nginx, uwsgi prints ModuleNotFoundError: No module named 'django' My uWsgi config: [uwsgi] plugins=python3 chdir=%d home=%dBASE_ENV socket=%duwsgi.sock virtualenv=./BASE_ENV pythonpath=%dBASE_ENV/lib/python3.6 module=reactTest.wsgi:application env=DJANGO_SETTINGS_MODULE=reactTest.settings master=true enable-treads=True processes=1 threads=%k logyo=/var/log/reactTest/reactTest.uwsgi.log chmod-socket=750 chown-socket=daneal:www-data uid=www-data gid=www-data vacuum=true http=:8000 -
In python, how to manage importing and using different class functionality?
I have two python classes, 'x', 'A' and 'B'. Here I am using class x's method in class A and class B class x: def display(self): print ("Hello python") class A: **# case 1** from . import x **# class level import** x_object = x() **# class level object** def my_method(self): x_object.display() class B: **#case 2** def my_method(self): from . import x **# method level import** x_object = x() **# method level object** So,in above scenarios I used class level import and object creation and method level import and object creation, my questions are as- which is best approach considering performance? how memory utilization work for both scenario? In above scenario, if I am using "my_method()" very frequently from django view. There will be 10000 concurrent requests accessing view from which method "my_method" is being called? is there any best way to use different class functionality in django view which give max performance and best memory management Thanks in advance. -
django.db.utils.ProgrammingError: column "projectfinancialtype" of relation "WorldBank_projects" does not exist
I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database. But while running 'python manage.py fetch' I am getting this error: django.db.utils.ProgrammingError: column "projectfinancialtype" of relation "WorldBank_projects" does not exist Here's the traceback: Traceback (most recent call last): File "/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column "projectfinancialtype" of relation "WorldBank_projects" does not exist LINE 1: INSERT INTO "WorldBank_projects" ("project_id", "projectfina... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/aggregator/WorldBank/management/commands/fetch_wb.py", line 60, in handle Projects.objects.create(**pdata) File "/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/python/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 923, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 962, in _do_insert using=using, raw=raw) File "/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, … -
Django 1.10 Need help using CreateView to add data in model which has relationship with other models(e.g. Classroom->School->User)
My django version is 1.11 and new to Django using CreateView for multiple tables. I have been trying to link the 3 models i.e. User(django built-in), School and Classroom. I need to create a new classroom which has relationship with the School and User model so how can add them to the Classroom model when creating a new class. I have the following simplied version of the code, In urls.py of app named basic_app, url(r'^login/$', views.user_login, name='user_login'), url(r'^class/(?P<pk>\d+)/$',views.ClassroomView,name='classroom_list'), url(r'^class/create/(?P<pk>\d+)$',views.ClassroomCreateView.as_view(),name='createClassroom'), In models.py, from django.contrib.auth.models import User from django.db import models from django.core.urlresolvers import reverse class School(models.Model): #1-1 relationship with django built-in User model user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name def get_absolute_url(self): return reverse("basic_app:detail",kwargs={'pk':self.pk}) class Classroom(models.Model): school = models.ForeignKey(School, on_delete=models.CASCADE) class_name = models.CharField(max_length=256) desc = models.CharField(max_length=256) def __str__(self): return self.class_name When the user click on the following link after login, <a href="{% url 'basic_app:createClassroom' pk=user.pk %}">Create Classroom In views.py, def user_login(request): if request.method == 'POST': # First get the username and password supplied username = request.POST.get('username') password = request.POST.get('password') # Django's built-in authentication function: user = authenticate(username=username, password=password) if user: #Check it the account is active if user.is_active: # Log the … -
AttributeError: 'Options' object has no attribute 'get_all_related_objects'
I am trying to implement https://github.com/tomwalker/django_quiz in my project. When I am running server I am getting this error. I am beginner please help. File "C:\Python36-32\lib\site-packages\model_utils\managers.py", line 106, in _get_subclasses_recurse rel for rel in model._meta.get_all_related_objects() AttributeError: 'Options' object has no attribute 'get_all_related_objects' -
Removing # from url of angularJS for SEO with backend as Django
I know removing hash from AngularJS is pretty straightforward but the problem is that the backend is in Django. So, the app works unless the page is refreshed using "F5". so, http://127.0.0.1:8000/account works if the button is clicked but refreshing the page gives me Page not found as the server searches for it in urls.py file Can someone please suggest me any fix for this ? -
How to integrate Vue cordova mobile app with django rest & django channels as backend?
i have a real time web app chat created using django, django rest framework and django channels. And now i want to create android and ios app, is it possible to connect with cordova and framework7 and vue in mobile app? how to integrate it? thanks for your help -
In django, Is it ok to write duplicate methods in different applications if method code is small?
I am working on web api using django. In this I have categorized functionality with different applications. I need suggestion for following scenario- Suppose I have three applications in a project, app1, app2 and app3 There is one function with name func(), func() require in app1 and app2 and may require in app3 in future. This function has same code, require same parameters. So, should I write func() in app1 and app2, also if require in app3. or write in only app1 and call it into app2. which is best approach for above scenario? does creating class object of class from app1 and calling method func() from another application cause performance issue if that class contains lot of code? or simply write a new method in application even though it is redundant Please suggest me best approach. Thanks in advance -
NoReverseMatch: Django URL
I Had everything Linking the way it should. Now I cannot display the products in the product detail view. I added in CreateView, UpdateView, DeleteView to edit the database. Now the CreateView, UpdateView, DeleteView all work fine but the actual links to the detailed product view gives me the Error: Reverse for 'category_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['products/categories/(?P<pk>\\d+)$'] The Information shows up fine in list view urls.py url(r'^$', views.index, name='index'), url(r'^products/$', views.ProductListView.as_view(), name='products'), url(r'^products/(?P<pk>\d+)$', views.ProductDetailView.as_view(), name='product_detail'), url(r'^categories/$', views.CategoryListView.as_view(), name='categories'), url(r'^categories/(?P<pk>\d+)$', views.CategoryDetailView.as_view(), name='category_detail'), url(r'^categories/create/$', views.CategoryCreate.as_view(), name='category_create'), url(r'^categories/(?P<pk>\d+)/update/$', views.CategoryUpdate.as_view(), name='category_update'), url(r'^categories/(?P<pk>\d+)/delete/$', views.CategoryDelete.as_view(), name='category_delete'), url(r'^products/create/$', views.ProductCreate.as_view(), name='product_create'), url(r'^products/(?P<pk>\d+)/update/$', views.ProductUpdate.as_view(), name='product_update'), url(r'^products/(?P<pk>\d+)/delete/$', views.ProductDelete.as_view(), name='product_delete'), ] models.py class Category(models.Model): """ Model For a product category """ c_name = models.CharField(max_length=200, help_text="Enter a Product Category: ") def __str__(self): """ String Representation for the Model object """ return self.c_name def get_absolute_url(self): """ Return an absolute URL to access a product instance """ return reverse('category_detail', args=[str(self.id)]) class Product(models.Model): p_name = models.CharField(max_length=200) description = models.TextField(max_length=4000) price = models.DecimalField(max_digits=6, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') quantity = models.PositiveIntegerField() featured_image = models.CharField(max_length=300) def __str__(self): """ String Representation for the Model object """ return str(self.p_name) + "€" + str(self.price) def get_absolute_url(self): """ Return an absolute URL to access a …