Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can someone explain what I did wrong to get this error? "ERROR in main Module not found: Error: Can't resolve "
I have been following a django-react tutorial and ran into a problem with the command npm run dev. I thought it was a problem with the webpack file but maybe not. This is the error that I am receiving: [error message][1] [webpack file][2] [package.json][3] [file structure and app.js][4] Sorry if anything about my problem is unclear this is my first post so let me know if I can clarify anything. Any help would be greatly appreciated. [1]: https://i.stack.imgur.com/vCK8g.png [2]: https://i.stack.imgur.com/eqYai.png [3]: https://i.stack.imgur.com/Yea1b.png [4]: https://i.stack.imgur.com/dLBXd.png -
Django cookiecutter Project code won't run
I'm currently working on a django project built with django cookiecutter. I'm running both redis server and the redis client but anytime I run the django server it keeps giving the below error raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the CELERY_BROKER_URL environment variable Below is the configurations of my .env file in my config folder DEBUG=True SECRET_KEY=12345 EMAIL_USE_TLS=True EMAIL_HOST=smtp.gmail.com EMAIL_PORT=587 EMAIL_HOST_USER=darkolawrence@gmail.com EMAIL_HOST_PASSWORD=********** DEFAULT_FROM_EMAIL=noreply@gmail.com BRAINTREE_MERCHANT_ID=5pbrjk4gmztd5m8k6dg BRAINTREE_PUBLIC_KEY=by84t6rfx9nz3vs6kegw BRAINTREE_PRIVATE_KEY=202056899b37713b1faeb093207160ff2e BROKER_URL=amqp:// CELERY_RESULT_BACKEND=db+sqlite:///results.sqlite -
Deployed django database and want to pull changes but don't want to delete what's in there
I used the django rest api framework to make the backend to my first website. I've changed the models and migrated the changes, and they work locally, it's just that I don't know how to get those changes to the production server that I'm hosting with pythonanywhere. Initially I didn't have a .gitignore in my repository, and I added one in order to not track the local db.sqlite3 file. But now when I pulled in production it was just deleting all these files so I hard reset to a previous commit. So how do I pull these changes and migrations properly without deleting my database? Thanks! -
im getting an error " Cannot resolve keyword 'group' into field. " trying to filter group model in admin.py
i have a model Transaction class Transaction(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) and admin.py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference', 'familymember__name'] inlines = [FamilyGroupInline, FamilyMemberInline] def save_model(self, request, obj, form, change): obj.Group = request.user.groups.all() print(obj.Group) super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(group__name__in=request.user.groups.all()) im trying to override save_model for each user in a group and then get a query_set for each group. the main purpose is i want each group to access its own Transaction. and then im getting this error : Cannot resolve keyword 'group' into field. Choices are: chp_reference, familygroup, familymember, id, income_period, property_market_rent, rent_effective_date -
Is there any way to write an API that sends a list of objects without using serializers
I tried to do this: indata=[] for inc in Income.objects.filter(wallet=this_wallet): indict= {} indict= {'id': inc.id, 'title': inc.title, 'amount': inc.amount, 'describe': inc.describe, 'wallet': inc.wallet.name, 'Created_at': inc.Created_at, 'dateOccured': inc.dateOccured, 'category': inc.category} indata.append(indict) return JsonResponse(indata, encoder=JSONEncoder) but here is what happened: ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. After I checked I found that the loop I wrote to add each object as a dictionary to the list, does not even begin and I dont understand how is this for inc in Income.objects.filter(wallet=this_wallet): causing problem! The point is Ive done the same thing with another object type which has worked well: for t in Token.objects.all(): if search(t.token, tok): try: this_user = Token.objects.get(token=t.token).user except Token.DoesNotExist: context = {} context['result'] = 'user-not-found' return JsonResponse(context, encoder=JSONEncoder) so is there anyone who can help me understand whats happening here or how I can fix this? ^-^ -
Django | How To Link Dynamic Data to Some Other Dynamic Data
I'm working on a IP inventory project and have the database model setup along with search working. I setup another Model and imported my Nessus Vulnerability data. I am trying to link the IP address from my inventory search result to the another view to show the info from the other model but I cant seem to get the filter right. I get all the records or none when I click on the link. Any direction would be appreciated! Here is the function: def nessusDATA(request): items = NessusReports.objects.filter(Host=IPs.IP_Address) context = { 'items': items, } return render(request, 'nessusdata.html', context) Here is the link: <td><a href="{% url 'nessusDATA' %}">{{item.IP_Address}}</td> Here is the Model: class NessusReports(models.Model): Risk = models.CharField(max_length=100, blank=True) Host = models.CharField(max_length=100, blank=True) Here is the URP.py path('nessusDATA/str:Host', views.nessusDATA, name='Host'), -
python-decouple | The SECRET_KEY setting must not be empty
The project was created using Django 3.1.1. It was recently updated it to Django 3.1.4 and it worked fine. Afterwards, python-decouple 3.3 was installed and it also worked fine. We deleted our testing database (on purpose) to see if everything was fine and this ocurred. When running python manage.py makemigrations the following error apprears Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "P:\crm\env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "P:\crm\env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "P:\crm\env\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "P:\crm\env\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "P:\crm\env\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "P:\crm\env\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "P:\crm\env\lib\site-packages\django\core\checks\templates.py", line 22, in check_setting_app_dirs_loaders for conf in settings.TEMPLATES File "P:\crm\env\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "P:\crm\env\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "P:\crm\env\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\rodri\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in … -
Can you get the request method in a DRF ModelViewSet?
I am building a Django chat app that uses Django Rest Framework. I created a MessageViewSet that extends ModelViewSet to show all of the message objects: class MessageViewSet(ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSerializer This chat app also uses Channels and when a user sends a POST request, I would like to do something channels-realted, but I can't find a way to see what kind of request is made. Is there any way to access the request method in a ModelViewSet? -
How to use 2 filters when querying from a database, and show items from both filters id Django
This is my code: video_object = video.objects.filter(category=category).filter(show_after_time__lt=datetime.datetime.now()).order_by("-show_after_time") I want to make the filter either 'category' or another variable, say 'other_category', but it would give me items that have either 'category' or 'other_category'. How do I do that? -
CircularDependencyError on Foreign Keys Pointing to Each Other Django
I get a circular dependency error that makes me have to comment out a field. Here is how my models are set up: class Intake(models.Model): # This field causes a bug on makemigrations. It must be commented when first # running makemigrations and migrate. Then, uncommented and run makemigrations and # migrate again. start_widget = models.ForeignKey( "widgets.Widget", on_delete=models.CASCADE, related_name="start_widget", null=True, blank=True, ) class Widget(PolymorphicModel): intake = models.ForeignKey(Intake, on_delete=models.CASCADE) By the way, Widget's PolymorphicModel superclass is from here. Why is this happening and how can I solve it without having to comment out over and over again? Thanks! -
I want to go to the default page ("/") after login (django view problem)
I want to go to the default page ("/") after login The current login process is as follows. Thanks if you let me know what I need to modify to change the redirect url to "/" url pattern path('login/', views.login, name='login'), views.py login = LoginView.as_view(template_name="accounts/login_form.html") templates {% extends "accounts/layout.html" %} {% block content %} <!-- .container>.row>.col-sm-6.offset-sm-3 --> <div class="container"> <div class="row"> <div class="col-sm-6 offset-sm-3"> {% include "_form.html" with submit_label="login" %} </div> </div> </div> {% endblock content %} -
Django - For the html in the subdirectory /snippets in accounts - TemplateDoesNotExist at /friend_request/user_id/
I am facing an error that is very common, if the template directory is not assigned in the TEMPLATES in settings.py The problem ist, that the app overall works and I get the error "TemplateDoesNotExist at /friend_request/user_id/" when I want to access an .html file in a subdirectory. Here the Settings.py TEMPLATES TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'accounts/templates/accounts')], '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', ], }, }, ] I assigned the proper context, getting passed to the sociel.html file containing the link to my friend_requests.html file in the subdirectory /snippets here the view in views.py def friend_requests(request, *args, **kwargs): context = {} user = request.user user_id = None friend_requests = None if user.is_authenticated: user_id = user.pk account = Account.objects.get(pk=user_id) if account == user: friend_requests = FriendRequest.objects.filter(receiver=account, is_active=True) context['friend_requests'] = friend_requests else: return HttpResponse("You can't ciew another users fried requests.") else: redirect("login") return render(request, "friend_requests.html", context) and here the reference in social.html <a href="{% url 'friend_requests' 'user_id' %}"><p id="rd_contact">Requests</p></a> the reference in urls.py looks like this path('friend_request/<user_id>/', views.friend_requests, name='friend_requests'), I already found one contribution here on stackflow that described a similar problem, that did not answered my problem -
Django link an image in templates to image dir
I'm recently was learning and was wondering how to connect an image to the media folder. Here is what i have the car object has a field image which points to the directly to the image for example car.image here will have cars/f1_ylNVV23.jpg output but the image is still not showing. What should I do ? -
Why can't I log into Django users with valid credentials, but can log into my original superuser?
I have this issue in my django project where users cannot login after creating an account. The user credentials are correct so everything should be working, but I guess I forgot to properly connect something while building my Customer User Model. Looking at my admin page, I see users in the database. I also cannot log into a superuser version of the account (changing superuser = True) when trying to de-bug the error. I've added some recommendations I found online such as SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False SESSION_ENGINE = 'django.contrib.sessions.backends.db' in my settings, but still no success. I'm only able to log into my original super-user that I created. Code below: models.py class CustomAccountManager(BaseUserManager): def create_superuser(self, email, user_name, first_name, last_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, user_name, first_name, last_name, password, **other_fields) def create_user(self, email, user_name, first_name, last_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) if not user_name: raise ValueError(_('You must provide a username')) if not first_name: raise ValueError(_('You must provide your first name')) if … -
Documents classification with variable set of labels
I want to create a model where a user can define a set of labels for the purpose of classification of documents. Each label for that document should also have a probability (float) that that document belongs to that label. So this is what I have for my model with 3 labels (news, business, sports): class Document(models.Model): document_name = models.CharField(max_length=100) proba_label_news = models.DecimalField(max_digits=5) proba_label_business = models.DecimalField(max_digits=5) proba_label_sports = models.DecimalField(max_digits=5) ... But of course there could be more labels what a user can define at the start of a classification project and what a developer can't foresee. I tried manytomany as an alternative but when I create a Label model and define a new label as "news" than I can't have a different probability for each document label, right? So what is the django way of solving this problem? -
ManyToMany django groups and users model with save_model()
i have a model Transaction that has some tables as shown below.. models.py : class Transaction(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) and in the admin.py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference', 'familymember__name'] inlines = [FamilyGroupInline, FamilyMemberInline] def save_model(self, request, obj, form, change): obj.user = request.user super().save_model(request, obj, form, change) # def get_queryset(self, request): # qs = super().get_queryset(request) # if request.user.is_superuser: # return qs # return qs.filter(group__in=request.user.groups.all()) i know this methods are broke, but i been struggling a lot with it im trying to override the save_model() and get_queryset() functions in the admin.py but im not sure how to do it. what im trying to do is for example i have 2 groups and in each group i will add certain amount of users. lets say i have (group1) and inside it i have users 'edy' and 'tom' inside it, and (group2) inside it 'sara' and 'laura', When edy makes a Transaction i want only (group1) users to access this transaction. same goes for (group2). and i dont want to create a group table inside the Transaction model, … -
Convert nested dictionary to url encoding as outputted from encodeURIComponent
I have this url encoded string (which is produced by the jQuery datatables library and looks to be outputted from the built in JavaScript encodeURIComponent function)- draw=1&columns%5B0%5D%5Bdata%5D=&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=false&columns%5B0%5D%5Borderable%5D=false&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=supplier__name&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=ref&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=period__fy_and_period&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=true&columns%5B3%5D%5Borderable%5D=true&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B4%5D%5Bdata%5D=date&columns%5B4%5D%5Bname%5D=&columns%5B4%5D%5Bsearchable%5D=true&columns%5B4%5D%5Borderable%5D=true&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B5%5D%5Bdata%5D=due_date&columns%5B5%5D%5Bname%5D=&columns%5B5%5D%5Bsearchable%5D=true&columns%5B5%5D%5Borderable%5D=true&columns%5B5%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B5%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B6%5D%5Bdata%5D=total&columns%5B6%5D%5Bname%5D=&columns%5B6%5D%5Bsearchable%5D=true&columns%5B6%5D%5Borderable%5D=true&columns%5B6%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B6%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B7%5D%5Bdata%5D=paid&columns%5B7%5D%5Bname%5D=&columns%5B7%5D%5Bsearchable%5D=true&columns%5B7%5D%5Borderable%5D=true&columns%5B7%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B7%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B8%5D%5Bdata%5D=due&columns%5B8%5D%5Bname%5D=&columns%5B8%5D%5Bsearchable%5D=true&columns%5B8%5D%5Borderable%5D=true&columns%5B8%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B8%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=1&order%5B0%5D%5Bdir%5D=asc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false Which I convert to a nested dict using this package - https://github.com/bernii/querystring-parser. {'draw': '1', 'columns': {0: {'data': '', 'name': '', 'searchable': 'false', 'orderable': 'false', 'search': {'value': '', 'regex': 'false'}}, 1: {'data': 'supplier__name', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 2: {'data': 'ref', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 3: {'data': 'period__fy_and_period', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 4: {'data': 'date', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 5: {'data': 'due_date', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 6: {'data': 'total', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 7: {'data': 'paid', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 8: {'data': 'due', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}}, 'order': {0: {'column': '1', 'dir': 'asc'}}, 'start': '0', 'length': '10', 'search': {'value': '', 'regex': 'false'}} How can I reverse this? I'm half there after managing to convert it to the decoded URL … -
Why I cannot register '.as_view()' in the Django router (using djangorestframework-simplejwt)?
I have been trying to add djangorestframework-simplejwt to my webapp and whenever I use the router to add the views (see the 2 commented routers in the code below) - I get an error (see traceback). When adding the urls as the documentation says - under the urlpatterns variable - it works without any errors. I would like to know why this isn't working through the router.register(..) and for the sake of good order (and my OCD), is it possible to move it out of the urlpatterns variable to the router. from django.urls import path, include from rest_framework import routers from . import views from django.conf.urls import url from django.contrib import admin from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) app_name = 'myapi' router = routers.DefaultRouter() router.register(r'posts', views.PostViewSet) router.register(r'user', views.UserViewSet) router.register(r'likes', views.LikesViewSet) # router.register(r'token',TokenObtainPairView.as_view()) # router.register(r'token/refresh',jwt_views.TokenRefreshView.as_view()) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] traceback: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/test/anaconda3/envs/ppproject/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/home/test/anaconda3/envs/ppproject/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/test/anaconda3/envs/ppproject/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/test/anaconda3/envs/ppproject/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/test/anaconda3/envs/ppproject/lib/python3.9/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File … -
Using translate field for 'unique' rises NameError, django-parler
I've recently installed django-parler==2.2 and when I rewrite my model to inherit from TranslatableModel and then try to makemigrations I get the following error: main_menu_slug = models.SlugField(max_length=120, unique=main_menu_item) NameError: name 'main_menu_item' is not defined Everything runs fine when I inherit from models.Model. Here is the code: class MenuItem(TranslatableModel): translations = TranslatedFields ( main_menu_item = models.CharField(max_length=60), main_menu_slug = models.SlugField(max_length=120, unique=main_menu_item) ) I've just started using this module, so possibly it is something trivial but I couldn't find the solution. What I am doing wrong? -
Groups model and Users model - ManyToMany field django admin
Im hassling for weeks now, hope someone could help. i have django admin page, with some apps, im trying to make use of the groups model which has ManyToMany relation with Users model, which come with django. first let me show you my Transaction model, models.py class Transaction(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) and in the admin.py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference', 'familymember__name'] inlines = [FamilyGroupInline, FamilyMemberInline] def save_model(self, request, obj, form, change): obj.user = request.user print(obj.user) super().save_model(request, obj, form, change) # def get_queryset(self, request): # qs = super().get_queryset(request) # if request.user.is_superuser: # return qs # return qs.filter(group__in=request.user.groups.all()) what im trying to do I want to make for example 3 groups in the admin page, each group will have certain amount of users, users are not super users. for example (Group1) will have 'edy' And 'tom' in it, (group2) have 'sara' and 'laura' in it. when edy makes a new transaction. i want this transaction whos made by edy be available and editable by (group1) members only and same goes for (group2). so what im struggling … -
Model is only updated in the Django Administration app and not in my app
I have just noticed that the model that I am displaying in my app is only showing new items that have been entered in the Django Administration app, and isn't showing anything that I enter directly from my own application. Could anyone explain what is going on? Here is my models.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils import timezone class Ticket(models.Model): """ Add a ticket """ title = models.CharField(max_length=225,blank=False) content = models.TextField() created_date = models.DateTimeField(auto_now_add=True) published_date = models.DateTimeField(blank=True, null=True, default=timezone.now) views = models.IntegerField(default=0) upvotes = models.IntegerField(default=0) image = models.ImageField(upload_to="img", blank=True, null=True) def __unicode__(self): return self.title and here is my admin.py in the same app: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import Ticket admin.site.register(Ticket) -
Alternative to raising Http404 from within a function call, (Django FormView)?
Hear me out. I have a class based FormView which renders a form with just one field as set of radio select buttons. The select options are based on a dynamic queryset that is passed in the kwargs when the form is initialised (see full code for the view below) def get_form_kwargs(self, **kwargs): """ Provides keyword arguemnt """ kwargs = super(ConfirmTripView, self).get_form_kwargs() trips = self.get_trips_queryset(self.gte_dates, self.lt_dates) kwargs.update({"trips": trips}) return kwargs This queryset is determined in the view logic by a database query and various other filters using values stored in the session. I have quite a few methods in play so that the same queryset is formed in both request.POST and request.GET. Specifically, I call a method def get_available_trips(self, destination, passengers): The resulting queryset is returned, passed and filtered further in other methods. I am considering a situation where this initial query returns no results. The methods that follow would raise errors and ultimately the form would not be rendered and it would be quite a catastrophe. Therefore I would need to break out of the flow somehow and instead render a message that says something like 'Sorry there is no availability for this selected trip'. I have only managed … -
Python Fast and efficient string and substring matching
Say I have a list of cars mercedes, lambo, ect. Each car object has a sublist of car models, aclass, gclass, ect. Both the Car top level class and the sub Model class has an image_url_string attached to it. see below. [ { 'car': 'mercedes', picture: 'mercedes_image_url' 'model': [ { car: 'aclass', picture: 'aclass_image_url' }, { car: 'gclass', picture: 'gclass_image_url' }, ] }, { 'car': 'lambo', picture: 'lambo_image_url' 'model': [ { car: 'urus', picture: 'urus_image_url' }, { car: 'huracan', picture: 'urus_image_url' }, ] } ] Question: Given a string, I need a function say getCarOrCarModelImage, that if the string given starts with a car, => returns the car's image_url if the string given starts with a car then a hyphen - then the model eg. mercedes - aclass => returns the model's url, Else it returns false The function should accommodate excess space errors in the given string Here are some instances: // True mercedes -> returns mercedes_image_url mercedes afagasfgagasdf_random_string -> returns mercedes_image_url mercedes -aclass asdfgafadsf_random_string -> returns aclass_image_url lambo -urus dasfddsag_random_string -> returns urus_image_url // with excess space errors lambo -urus dasfddsag_random_string -> returns urus_image_url lambo dasfddsag_random_string -> returns lambo_image_url // False dasfddsag_random_string -> returns false -urus dasfddsag_random_string -> … -
Django Foreign key in hidden form field
I'd like to hide a Foreign Key field in a form created from a Model in a View. Here is the Model : class Order(models.Model): class Meta: ordering = ['unity_price'] item = models.ForeignKey(Item, on_delete=models.CASCADE) user = models.ForeignKey(authModels.User, on_delete=models.CASCADE, default=1) order_quantity = models.IntegerField(default=0) unity_price = models.FloatField(default=0) end_validity_date = models.DateTimeField(default=timezone.now() + datetime.timedelta(days=30)) is_sell = models.BooleanField(default=True) def __str__(self): if self.is_sell: return 'sell ' + str(self.order_quantity) + ' ' + self.item.item_text + ' at ' + str(self.unity_price) return 'buy ' + str(self.order_quantity) + ' ' + self.item.item_text + ' at ' + str(self.unity_price) Here is the Form : from .models import Order class OrderForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.fields['user'].widget = HiddenInput() self.fields['item'].widget = HiddenInput() class Meta: model = Order fields = ('item', 'user', 'order_quantity', 'unity_price', 'end_validity_date', 'is_sell',) And here is the View : class DetailView(FormMixin, generic.DetailView): model = Item template_name = 'bourse/detail.html' form_class = OrderForm def get_success_url(self): return reverse('bourse:detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) context['form'] = OrderForm(initial={'post': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() form.fields['item'].initial = self.get_object() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): model_instance = form.save(commit=False) model_instance.user = self.request.user model_instance.item = self.get_object() print (model_instance.item) model_instance.save() return … -
How to get choicefield selected value Django Forms
I have taken an empty Choicefield called product_attr. I get attributes for that product via Ajax Call On Change event. When I go to update the form, the Attributes field does not show the value I submitted. How can I get the existing value of product_attr field in the form while editing/updating. Please help me to get out of here. forms.py class PurchaseOrderDetailsForm(forms.ModelForm): product = forms.ModelChoiceField(label=('Product'), required=True, queryset=Product.objects.all(), widget=Select2Widget()) product_attr = forms.CharField(label=('Attributes'), required=False, widget=Select2Widget(choices=[])) Get attribute value on ajax request: def load_attrs(request): product = request.POST.get("product") attrs = ProductAttributes.objects.filter(product=product).values('product', 'size__name', 'colour__name','cupsize__name') return render(request, 'main/purchase/attr_dropdown_list_options.html', {'attrs': attrs}) views.py: (form update) class PurchaseOrderItemsUpdate(UpdateView): model = PurchaseOrder form_class = PurchaseOrderForm template_name = 'main/purchase/index.html' def get_context_data(self, **kwargs): kwargs['object_list'] = PurchaseOrder.objects.order_by('-id') data = super(PurchaseOrderItemsUpdate, self).get_context_data(**kwargs) if self.request.POST: data['order_details'] = PurchaseOrderItemsFormset(self.request.POST, instance=self.object) else: data['order_details'] = PurchaseOrderItemsFormset(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() order_details = context['order_details'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if order_details.is_valid(): order_details.instance = self.object order_details.save() return super(PurchaseOrderItemsUpdate, self).form_valid(form)