Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom Form Field Render using UpdateView not Saving Data
I am trying to use custom HTML to render form field elements. However, now the data is not saving. The data is saving if I use the default form.as_p method. Related template: <!--DOES NOT SAVE DATA--> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.description }} <input type="submit" value="Update"/> </form> <!--SAVES DATA--> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Update"/> </form> Related UpdateView: class ProfileEditView(UserPassesTestMixin, UpdateView): model = Profile form_class = ProfileCreateForm template_name = 'update_profile_backup.html' def get_success_url(self): return reverse('profile', kwargs={'pk': self.object.pk}) def test_func(self): obj = self.get_object() print(obj.user == self.request.user) return obj.user == self.request.user Related ModelForm: class ProfileCreateForm(forms.ModelForm): class Meta: model = Profile fields = 'platform', 'content_niche', 'youtube_channel_id', 'description','profile_img', 'v_id_0', 'v_id_0_title', 'v_id_0_desc', \ 'v_id_1', 'v_id_1_title', 'v_id_1_desc', 'v_id_2', 'v_id_2_title', 'v_id_2_desc' Is it because the custom render method is not validating the form data? If so, how would I do that with an updateview? -
Wrong conversion of datetime timezone aware object in template Django
I have 2 datetime object with timezone Europe/Berlin and US/Eastern that I initially set with pytz. datetime.datetime(2019, 6, 11, 10, 20, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>) datetime.datetime(2019, 6, 11, 12, 16, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>) These times should be displayed as 10:20AM and 12:16PM respectively. However, in my django template they are different, for example: {{ value.departure_time.date_time|time:'f A'}} # >> 8:20 AM instead of 10:20AM Any thoughts? -
What is the correctly way to delete edges with orientdb OGM in django rest framework?
I don't know how to create a method to delete edges in django rest framework, using orientdb OGM. I'm using pyorient==1.5.5 and OrientDB 3.0.18 version. I have two vertex Classes: ousers, ocompany. Also I have two relationships (edges) Classes: ofriends, oworksat. So for example: To make a ofriends relationship I need two ousers. And to make a oworksat relationship I need one ouser and one ocompany. Every relationship has it own cluster id. I know that I can access to these functions: (Pdb) dir(graph) ['PROPERTY_TYPES', '_GROOVY_GET_DB', '_GROOVY_NULL_LISTENER', '_GROOVY_TRY', 'class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', '_last_cred', '_last_db', '_last_user', 'batch', 'both', 'bothE', 'build_mapping', 'clear_registry', 'client', 'coerce_class_names', 'coerce_class_names_to_quoted', 'compute_all_properties', 'config', 'create_all', 'create_class', 'create_edge', 'create_edge_command', 'create_function', 'create_props_mapping', 'create_vertex', 'create_vertex_command', 'delete_vertex', 'delete_vertex_command', 'drop', 'drop_all', 'drop_class', 'edge_from_record', 'edges_from_records', 'element_from_link', 'element_from_record', 'elements_from_links', 'elements_from_records', 'export', 'get_edge', 'get_element', 'get_vertex', 'gremlin', 'guard_reserved_words', 'inE', 'in_', 'include', 'init_broker_for_class', 'list_superclasses', 'ocompany', 'ofriends', 'open', 'ousers', 'out', 'outE', 'oworksat', 'populate', 'property_from_schema', 'props_from_db', 'props_to_db', 'query', 'registry', 'save_element', 'scripts', 'server_version', 'strict', 'toposort_classes', 'valid_element_base', 'vertex_from_record', 'vertexes_from_records'] If I do: graph.delete_vertex("#21:0") It works good and deletes #21:0 ouser vertex row, which is part of ofriends and oworskat relationships, so also, … -
Dynamically added hidden input to Django form results in KeyError
In my code I have jQuery method with which I am adding value dynamically to my form on submit. The code looks like this: form_page.html <form id="objectForm" class="form-horizontal" action="" method="post"> {% csrf_token %} {% include 'manage/form-template.html'%} <button id="submitBtn">submit</button> </form> <script> $(document).ready(function(){ $("#submitBtn").click(function(){ $("#objectForm").submit(function(){ $("<input />").attr("type", "hidden") .attr("name", "dates") .attr("value", "something") .appendTo("#objectForm"); return true; }); // Submit the form }); }); </script> views.py class ObjectUpdateView(UpdateView): template_name = 'manage/object_form.html' form_class = ObjectEditForm def get_success_url(self): #... def form_valid(self, form): clean = form.cleaned_data['dates'] print('Dates: ', clean) return super(ObjectUpdateView, self).form_valid(form) forms.py class ObjectEditForm(forms.ModelForm): class Meta: model = Object fields = ['TestField'] This code is resulting in KeyError on the clean = form.cleaned_data['dates'] line. Debugging POST values in Chrome I can see that value itself is set properly. For some reason Django is not registering this. Can anyone suggest what I need to do, to access this value in Python? -
ajax not activating, taking me to a different page
the code works as I want but it takes me to a different page and have something like {"success": 1, "voteobj": 57}. I was informed ajax is the one for this but I'm not good at it. here's what I have. can someone check where I made an error and what I should do to fix it/? <script type="text/javascript"> jQuery(document).ready(function($) { $(".vote_form").submit(function(e) { e.preventDefault(); var btn = $("button", this); var l_id = $(".hidden_id", this).val(); btn.attr('disabled', true); $.post("vote/", $(this).serializeArray(), function(data) { if(data["voteobj"]) { btn.text("-"); } else { btn.text("+"); } }); btn.attr('disabled', false); }); }); </script> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <form method="post" action="{% url 'vote' %}" class="vote_form"> <li> [{{ post.votes }}] {{post}} {% csrf_token %} <input type="hidden" id="id_post" name="post" class="hidden_id" value="{{ post.pk }}" /> <input type="hidden" id="id_voter" name="voter" class="hidden_id" value="{{ user.pk }}" /> {% if not user.is_authenticated %} <p>login to vote</p> {% elif post.pk not in voted %} <button class="btn btn-primary">like</button> {% else %} <button class="btn btn-primary">dislike</button> {% endif %} </form> And following is my python code class JSONFormMixin(object): def create_response(self, vdict=dict(), valid_form=True): response = HttpResponse(json.dumps(vdict), content_type='application/json') response.status = 200 if valid_form else 500 return response class VoteFormBaseView(FormView): form_class = VoteForm def create_response(self, vdict=dict(), valid_form=True): response = HttpResponse(json.dumps(vdict)) response.status = 200 if … -
how to display a html file stored in s3 in aws in my django template?
I am trying to make free learning site . Content of mysite are stored in s3 in html format .How to embed that html code from s3 in to my django app. -
How to update object from within class?
If there is a better way to word this question please let me know. I am reformatting some code to better follow The Zen of Python and cannot seem to update an object inside a class. The previous code would try: to access the object for the value but if the object did not exist yet it would default to a value in the exception like this: def service_breakpoint_default(): try: sb_def = float(Settings.objects.values( 'service_breakpoint').last().get('service_breakpoint')) return sb_def except AttributeError: return 1700.00 This was accessed in a model as the default= value of a CharField like this: class Settings(models.Model): service_breakpoint = models.CharField( max_length=16, default=service_breakpoint_default) The problem with this code format is that there are about 20 attributes for the Settings class. Therefore it seems better to create all the "default" functions by using a class: class CreateSettings: def __init__(self, name, default): self.name = name self.default = default def getvalue(self): try: self.default = float(Settings.objects.values( str(self.name)).last().get(str(self.name))) return self.default except (NameError, AttributeError): return self.default service_breakpoint_default = CreateSettings('service_breakpoint', 1700.00) class Settings(models.Model): service_breakpoint = models.CharField( max_length=16, default=service_breakpoint_default.getvalue()) The problem is that service_breakpoint_default.getvalue() in the Settings model does not seem to be updating the object in the database. It keeps reverting to the CreatingSettings.default('service_breakpoint_default') which is 1700.00. -
restricting user to like the post once in Views.py not in model
I know I can do this easily in models.py but I don't have like model in my app. I have post app and there's like field. so I want to restrict it in my views.py Here's my try but I don't understand why it won't restrict it @login_required def like_post(request, pk): if User.objects.filter(pk = pk, id = request.user.id).exists(): return HttpResponse('You already voted for this, cheater') else: liked_post = Post.objects.get(id=pk) count = liked_post.likes count += 1 liked_post.likes = count liked_post.save() return redirect('/community/post/%s' %liked_post.id) -
Error during template rendering Reverse for 'group-edit' not found. 'group-edit' is not a valid view function or pattern name
I ve an error when loading 'group_list.html' : Reverse for 'group-edit' not found. 'group-edit' is not a valid view function or pattern name. If I supress this href reference, it works but I need this to be able to edit a group instance this is my views.py for group_edit: def group_edit(request, group_id): group_form = GroupFormEdit(instance=Group.objects.get(id=group_id)) if request.method == "POST": group_form = GroupForm(request.POST, instance=Group.objects.get(id=group_id)) if group_form.is_valid(): group_form.save() messages.success(request, 'Group saved') # message for inform user of success - See messages in html file return redirect('home') else: group_form = GroupForm() return render(request, 'imports/group_edit.html', { "group_form": group_form, }) my group_list.html: {% block page %} <div class="panel-body"> <table class="table table-bordered table-hover table-striped col-md-3"> <thead class="thead-dark"> <tr class="text-center"> <th>Group Name</th> <th>Parent Name</th> </tr> </thead> <tbody> {% for group in groups %} <tr> <td scope="row" class="col-md-3"><a href="{% url 'group-edit' group.group_id %}">{{ group.group_name }}</a></td> <td class="col-md-3">{{ group.groupParent_id }}</td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} my urls.py: urlpatterns = [ path('', views.imports_last, name='home'), path('company_create/', views.company_create, name='company_creation'), path('group_create/', views.group_create, name='group_creation'), path('group_edit/', views.group_edit, name='group_edit'), path('group_list/', views.group_list, name='group_list'), ] and models.py: class Group(models.Model): group_id = models.AutoField(primary_key=True) groupParent_id = models.ForeignKey('self', blank=True, null=True, related_name='Parent', on_delete=models.CASCADE) group_name = models.CharField(max_length=100, null=False, blank=False, unique=True) def __str__(self): return '{}'.format(self.group_name) -
Django shop cart.py ı need size choice
My problem I have django shop project normaly my project working but my problem ı have only one quatity , ı wanna show quantit and size cohice fileds but when ım show ı dont add to cart detail html anyone help me ? -
Use ajax to make chat refresh sent message from database without reloading in django
Please I am create a messenger part in my web application on django and I want the site to show the new message that a user sent on screen without reloading the page. I know using ajax with update the back end without reloading the page but I want the front end to be updated as well. How can I do that -
No module named 'pagedown'
I am doing the following steps: activated virtual environment pip install django-pagedown Added pagedown to INSTALLED_APPS python manage.py collectstatic --noinput and tried python manage.py collectstatic added this in forms.py from pagedown.widgets import PagedownWidget INSTALLED_APPS = [ 'pagedown', ] Getting this error in VSCode that couldn't import PagedownWidegt, and getting above stated error in terminal. how do I solve it? Thank you -
transforming function based view to class based view
I think it should be simpler but here's my function based view with filter def withSub(request): post = Post.objects.filter(with_or_without_sub='WS') paginator = Paginator(post, 2) page = request.GET.get('page') post = paginator.get_page(page) content_dict = { 'posts':post, 'paginator':paginator } return render(request, 'community/withSub.html', content_dict) I simply want to switch it to class based view in a format as below, I just want to put filter to Post model as I did in function view class PostListView(ListView): model = Post template_name = 'community/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 4 #ordering = ['-date_posted'] queryset = Post.with_votes.all() def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: voted = Vote.objects.filter(voter=self.request.user) posts_in_page = [post.id for post in context["object_list"]] voted = voted.filter(post_id__in=posts_in_page) voted = voted.values_list('post_id', flat=True) context["voted"] = voted return context -
HTTP Error 500.0 - Internal Server Error Django on iis Error Code 0x00000067
I'm trying to makedjango web app work on IIS using wfastcgi Following This guide it gave me the error code 0x00000067 and here is my web.config file : <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="AccuManager" path="*" verb="*" modules="FastCgiModule" scriptProcessor="E:\projectInnoventiq\accuManager\venv\Scripts\python.exe|E:\projectInnoventiq\accuManager\venv\Scripts\wfastcgi.py" resourceType="Unspecified" /> </handlers> <httpErrors errorMode="Detailed" /> <tracing> <traceFailedRequests> <add path="*"> <traceAreas> <add provider="ASP" verbosity="Verbose" /> <add provider="ASPNET" areas="Infrastructure,Module,Page,AppServices" verbosity="Verbose" /> <add provider="ISAPI Extension" verbosity="Verbose" /> <add provider="WWW Server" areas="Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,FastCGI,WebSocket" verbosity="Verbose" /> </traceAreas> <failureDefinitions timeTaken="00:00:00" statusCodes="500" /> </add> </traceFailedRequests> </tracing> </system.webServer> </configuration> -
Django model for books
I want to define a class for books. A book consists of several chapters. A chapter consists of several sections. A section consists of several subsections. Is it okay to do it as follows? class Book(models.Model): chapters = models.ManyToManyField('Chapter') class Chapter(models.Model): sections = models.ManyToManyField('Section') class Section(models.Model): subsections = models.ManyToManyField('Subsection') class SubSection(models.Model): content = models.TextField() Or is there a better way? -
handling multiple values from html form in Django
Problem : I have a sample form where user can add his languages know whch is dynamic. I need to insert this in sqlite DB using Django. I am trying to get the data, but somehow i am not getting desired result. Issue : 1) unable to get the FK instance of PersonInfo ID 2) Not getting list of Language. If i display it shows only one language. from django.db import models # Create your models here. class PersonInfo(models.Model): firstname = models.CharField(max_length = 100) lastname = models.CharField(max_length = 100) phone = models.CharField(max_length = 20) email = models.CharField(max_length = 100) def __str__(self): return self.firstname class KnownLanguages(models.Model): languagename = models.CharField(max_length = 100) personinfo = models.ForeignKey(PersonInfo, on_delete = models.CASCADE) def __str__(self): return self.languagename Below is the code for Django View def addperson(request): personinfo = PersonInfo.objects knownlang = KnownLanguages if request.method == 'POST': if request.POST['firstname'] and request.POST['lastname'] and request.POST['languagename']: person = PersonInfo() lang = KnownLanguages() person.firstname = request.POST['firstname'] person.lastname = request.POST['lastname'] person.phone = request.POST['phone'] person.email = request.POST['email'] # person.save() print(person.firstname) print(person.id) lang.languagename = request.POST['languagename'] lang.personinfo = person # lang.save() print(lang) return render(request, 'dynamicaddfields/addperson.html', {'personinfo' : personinfo, 'knownlang': knownlang}) else: return render(request, 'dynamicaddfields/addperson.html', {'error' : 'Please fillout atleast First & Last Name and atleast one … -
how to play with ordering in class based view
I'm using class based view and for instance class PostListByMostViewedView(ListView): model = Post template_name = 'community/mostviewed_home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-views'] paginate_by = 5 Models.py class Post(models.Model): views = models.PositiveIntegerField(default=0) then posts are listed by view. but I have different model class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) I want to order by the number of post. I thought this would work ordering = ['-post.comment_set.count'] but this fails no such column: post.comment_set.count -
(Host Django Pythonanywhere) Manage.py collectstatic returns FileNotFoundError: [Errno 2]
Hi I deployed a python Django app on www.pythonanywhere.com, the app works fine, but when I try to run manage.py collectstatic I get this error here is my code at settings.py STATIC_URL = '/static/' STATIC_ROOT = '/home/djangopaste/DjangoPaste/djangohost/static' Project Directory to settings.py /home/djangopaste/DjangoPaste/djangohost/ Project Directory to manage.py /home/djangopaste/DjangoPaste/djangohost Traceback error File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/djangopaste/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/djangopaste/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/djangopaste/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/djangopaste/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/djangopaste/.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/home/djangopaste/.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect for path, storage in finder.list(self.ignore_patterns): File "/home/djangopaste/.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 131, in list for path in utils.get_files(storage, ignore_patterns): File "/home/djangopaste/.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/home/djangopaste/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/files/storage.py", line 315, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/home/djangopaste/DjangoPaste/djangohost/static'``` -
Django rendering template in view class
In an attempt to further understand the Django framework, I am writing a small test case. The app name is "login" and I have the following defined: urls.py: from django.urls import path from .views import Index urlpatterns = [ path('', Index.as_view(), name='index') ] views.py: from django.shortcuts import render from django.views.generic import TemplateView class Index(TemplateView): template_name = "/login/index.html" def get(self, request): render(request, self.template_name, None) Running into a problem loading the page: /login/templates/login/index.html index.html is located in the login app folder: TemplateDoesNotExist at /login/ What concepts am I missing here? -
how to pluralize with template tag
I forgot this, there was an easy built in template tag I could use. {{ post.comment_set.count }}comment if there's more than one comment then it should display comments. {{ post.comment_set.count|"something here" }}comment -
Django: get data from tables and display together using ListView
I want to display data from 2 tables (and more in the future), but something doesnt work in my code. my models.py: **imports** def home(request): context = {'users': Person.object.all(), 'emails': Email.object.all() } return render(request,'app/home.html',context) class PersonListView(ListView): model = Person template_name = 'app/home.html' context_object_name = 'users' and in my home.html {% extends "app/base.html" %} {% block content %} {% for user in users %} Displaying user attributes works fine {% endfor %} Here should be emails {% for email in emails %} This displaying doesnt work {% endfor %} {% endbock content %} So, displaying users works without any problem, but cant display anything form emails, but if I do it in shell, everything works well -
Django 2.2 Not Serving Static Files
I am currently working through some tutorials to enhance my knowledge of Django. In doing so, I decided to use to most recent version of Django. I have been able to overcome most of the divergences between my code and that of the tutorial except for one - static files are not being served. Now, I am not fully sure that the difference is strictly due to the Django version. Here is what is going on. I have the following project structure: settings.py STATIC_URL = '/static/' STATIC_FILES = ( os.path.join(BASE_DIR, "static"), ) STATIC_ROOT = os.path.join (os.path.dirname(BASE_DIR), "staticfiles", "static") TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], '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', ], }, }, ] What is interesting is that with this configuration, the project is able to find templates successfully. However, as mentioned above, it cannot find the static files. Why is that? Also, this tutorial sets up an unusual configuration in that the static and templates directories are located inside the main app's directory, whereas I typically have them one level higher, i.e., in the project root's directory. Could this be a part of the problem? What in the settings of this … -
Error connecting django-rq: ImportError: cannot import name get_failed_queue
Never worked with django-rq, redis. The problem should be solved easily, I think, but I do not know how. When I start the server, I get this error ImportError: cannot import name get_failed_queue I'm use Python 2.7 Full Traceback Unhandled exception in thread started by <function wrapper at 0x7f8d45706410> Traceback (most recent call last): File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver for pattern in resolver.url_patterns: File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/m0nte-cr1st0/work_projects/startapp/finbee/finbee/urls.py", line 27, in <module> url(r'^admin/rq/', include('django_rq_dashboard.urls')), File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django_rq_dashboard/urls.py", line 3, in <module> from . import views File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django_rq_dashboard/views.py", line 16, in <module> from rq import Queue, Worker, get_failed_queue, push_connection ImportError: cannot … -
django model design with different user types
I am just learning django so i thought of creating a project called job board to understand more in detail. I have drawn the following use case. People can register as job seekers, build their profiles and look for jobs matching their skillsets Companies can register, post jobs. Multiple representatives from a company should be able to register and post jobs. Independent Recruiter can create an account as well. Company can contact to those independent recruiter. How would be the model design for such use case? I am confused with the multiple user types in django. Some favors creating a user profile, while some favors using Groups. For now, I could only do the following class User(AbstractUser): ''' Abstract user because django recommends to start with custom user ''' username = None email = models.EmailField(_("Email Address"), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Company(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) I could create a model for User and Company. But i have no idea on handling multiple user types like user can be either job seeker or recruiter. Also multiple representatives from a company should be able to register and post jobs as well … -
RuntimeError: Model class rideshare.models.rideshare doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I have two separate projects kept under two different paths. I want to import model from one of my project coolpool to other project Ajaxpython but while doing this it is giving me the error. RuntimeError: Model class rideshare.models.rideshare doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS I kept my settings.py like below: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #'coolpool.rideshare', ] If i uncomment the last line it gives ModuleNotFoundError: No module named 'coolpool'. I have my model defined under coolpool.rideshare.models which i am not able to use in my files views.py in Ajaxpython project pasted below: from django.http import HttpResponse import datetime sys.path.insert(0, '/Users/user/Desktop/millo/coolpool') from rideshare.models import * print(sys.path) def validate_username(request): try: username = request.GET.get('username', None) data = { 'is_taken': ridesharerequests.objects.filter().exists() } if data['is_taken']: data['error_message'] = 'A user with this username already exists.' return JsonResponse(data) I don't have any idea what wrong i am doing here as i tried several different ways but still no luck. I can post content from other files as well if anyone needs it here.