Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I check activity in my app which is written in Django and Angular 4 and it is deployed on Heroku?
I created application based on REST API. Server is written in Django and has PostgreSQL database, web application is written in Angular 4. Both are deployed separately on Heroku. How can I check activity on this website? I would like to know how many people visited them, how money users is active etc. I short, I need all possible statistics. Any ideas? -
Running celery with supervisord unable to discover tasks
I am using celery 4.1.0 with Django-1.11 and supervisor 3.3.1. For some reason celery is unable to discover the tasks in apps (which are listed in INSTALLED_APPS) when I run celery worker via supervisor. When I run celery from command line it does show the tasks. For example, when I run celery from command line here is the output: Running from command line: /home/ubuntu/Env/oba/bin/celery worker -A oba -l DEBUG - ** ---------- .> transport: amqp://***:**@localhost:***// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 1 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . celery.accumulate . celery.backend_cleanup . celery.chain . celery.chord . celery.chord_unlock . celery.chunks . celery.group . celery.map . celery.starmap . contact.tasks.send_email_to_admin_for_member . contact.tasks.send_email_to_admin_for_visitor But when run via supervisord, the output from celery is: - ** ---------- .> transport: amqp://***:**@localhost:***// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 1 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . celery.accumulate . celery.backend_cleanup . celery.chain . … -
django RestFrameWork - set user to active
I have a model that related to User.I create user instance with is_active=False.I create some model that generate a token .i need to write some functionality ,if token given from user equals to token that related to user instance ,then account set to is_active=True . this is my structure : models.py: class FirstToken(models.Model): token = models.CharField(max_length=6, blank=True) def __str__(self): return self.token def save(self, *args, **kwargs): chars = string.ascii_lowercase + string.digits size = 6 self.token ="".join(random.choice(chars)for _ in range(size)) super(FirstToken, self).save(*args, **kwargs) class UserProfile(models.Model): """User Profile model """ user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='user_profile') phonenumber = models.CharField(validators=[phone_regex], max_length=17, null=True, unique=True) address = models.TextField(max_length=250) first_token = models.OneToOneField(FirstToken,on_delete=models.CASCADE, related_name='first_token',blank=True) def save(self, *args, **kwargs): token = FirstToken.objects.create() self.first_token = token super(UserProfile, self).save(*args, **kwargs) serializers.py class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile exclude = ['user','id','first_token'] extera_kwargs = { 'phonenumber' : {'validators': []}, } class ActivateUserSerializer(serializers.ModelSerializer): phonenumber = serializers.CharField() token = serializers.CharField() class Meta: model = UserProfile fields = ['phonenumber', 'token',] def validate(self, validated_data): token = validated_data.get('token') x = validated_data.pop('phonenumber') user = UserProfile.objects.get(phonenumber=x) if token == user.first_token: user.set_is_active = True user.save() else : raise serializers.ValidationError("not correct") return token the error i get is: 'str' object has no attribute 'items' what sould i do for performing to … -
how to handle same form on different pages (DRY)
I have a template called base.html. it contains a fixed search form at top of it. all of my other templates inherit from base.html. I want to my form works on every pages (right now I have 10 different pages). One silly solution is to handle form for every single view, but it is opposite of DRY. So how can I handle my form one time for all of views ? NOTE: base.html is just a template and is not used directly by a view. -
Django can't find my static files after changing to production settings and back
I've been trying to deploy my site this weekend and have thus been meddling with the settings. I one of the unpleasant surprises while doing this have been that my static files have seemingly stopped working on my site. My CSS files and javascript files don't work anymore, as if they aren't found by the site. The only thing I can remember doing with regards to static files was inserting this into settings.py: # The absolute path to the directory where collectstatic will collect static files for deployment. STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # The URL to use when referring to static files (where they will be served from) STATIC_URL = '/static/' I removed these settings and replaced them with the original STATIC_URL = '/static/' but alas, the problem remains. Why isn't Django finding my static files anymore? PS: As I'm a noob, I don't know exactly what is relevant from my project for you guys to see, but do let me know and I shall provide additional info. -
I need to create API to query data from Twitter based on search term
Hi i need some references to create API to query data from Twitter based on search term using Django, MongoDB, Elastic Search. It would be really helpful if any one have any references to help. -
How to Create new table(models) whenever a new record is created in Django without interrupt a running server
How to create separate table for each record in models (table with same fields for all models), It should happens whenever the new record in models in aa running server without interruption of server | Id | Station Name | GPS Location | Address | 1 | Station 1 | 35.211898, -101.969547 | Some where | | 2 | Station 2 | 43.793428, -102.658402 | Some where | | ... |.............. | ................... | ...... | | ... |.............. | ................... | ...... | | ... |.............. | ................... | ...... | | n |Station n | xx.xxxxxx, xx.xxxxx | xxxxxx | For these each entries I need separate table(Models) like below mentioned should create automatically , whenever a new record is added All Columns headings(Fields) are same in all the table(models) which are create for the record TABLE NAME: Station 1 | TimeStamp | Temperature | Humidity |...|...|...| 40th Column | |14-Jan-18 11:30:12 | 20.13 C | 15% |...|...|...| xxxxxx | |14-Jan-18 11:30:13 | 20.16 C | 15% |...|...|...| xxxxxx | |14-Jan-18 11:30:14 | 20.11 C | 15% |...|...|...| xxxxxx | |14-Jan-18 11:30:15 | 20.18 C | 15% |...|...|...| xxxxxx | . . . |20-Dec-18 16:14:30 | 30.74 C| … -
Django - admin filter to "Add..." page (Model with more then one FK)
I am trying to filter the "Test" content according to "Plan" selection. enter image description here While models looks like: class TestPlan(models.Model): test_plan_name = models.CharField(max_length=200) def __str__(self): return self.test_plan_name class Test(models.Model): test_plan = models.ForeignKey(TestPlan, on_delete=models.CASCADE) test_name = models.CharField(max_length=200) test_type = models.CharField(max_length=200) manual_ttc = models.IntegerField(default=0) priority = models.IntegerField(default=0) owner = models.CharField(max_length=200) drop_name = models.CharField(max_length=200) test_description = models.CharField(max_length=200) note = models.CharField(max_length=200) ac = models.CharField(max_length=200) def __str__(self): return self.test_name class Result(models.Model): plan = models.ForeignKey(TestPlan, on_delete=models.CASCADE) test = models.ForeignKey(Test) status = models.CharField(max_length=100) version = models.CharField(max_length=100) bug = models.CharField(max_length=100) result_path = models.CharField(max_length=100) def __str__(self): return self.status -
Django receive POST from webhook
Our App is receiving webhooks via POST from our payment processor. When I was building this function I originally had it to GET for testing purposes so I could use the URL to test paramaters. Everything worked fine but now I need to test with fake purchases which sends POST request to our URL. So I updated the code but no new webhooks are being saved in our database now. views.py @require_POST def webhook(request): template_name = 'payment/index.html' hook = Webhook() user = User.objects.get(id=request.POST.get('clientAccnum', '')) hook.user = user hook.clientSubacc = request.POST.get('clientSubacc', '') hook.eventType = request.POST.get('eventType') hook.eventGroupType = request.POST.get('eventGroupType', '') hook.subscriptionId = request.POST.get('subscriptionId', '') hook.timestamp = request.POST.get('timestamp', '') hook.timestamplocal = timezone.now() hook.save() hook.user.profile.account_paid = hook.eventType == 'RenewalSuccess' hook.user.profile.save() return render(request, template_name) models.py class Webhook(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False) clientSubacc = models.CharField(max_length=120, blank=True, null=True) eventType = models.CharField(max_length=120, blank=True, null=True) eventGroupType = models.CharField(max_length=120, blank=True, null=True) subscriptionId = models.CharField(max_length=120, blank=True, null=True) timestamp = models.DateTimeField(blank=True, null=True) timestamplocal = models.DateTimeField(blank=True, null=True) I'm firing POST requests now from our payment processor and their support is telling me webhooks are being fired but nothing new is saving in the db. This leads me to believe the views.py code is wrong. Anyway I can test this? -
Gunicorn not using right settings file Django?
In my wsgi.py I am conditionally setting DJANGO_SETTINGS_MODULE to two different files(local and production). On the server I have set "PROD" variable in /etc/profile if "PROD" in os.environ: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings_dev") But, still I am getting an error because right settings file is not being set. So maybe if condition isn't working. See below pic. My gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/myproject/myproject ExecStart=/usr/local/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/myproject/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target -
django server doesnt load css when it is run
I have all the static files, but for some reason only the normal html loads with no css. I have tried using collectstatic and creating a new project but it doesn't work on any. STATIC_URL is also specified along with static in the url.py . Nothing seem to be working. -
How to prefill certain fields in a new form with respect to the object detail in view in django
I am rendering a form inside a shop detail My form fields includes name, address, shop, booking_date I want to render the form inside of the object detail with only the shop name already prefilled because its inside of the shop detail the form is in -
show the diff result
x = diff(a, b) result: {'sat': {0: {'sat1': {0: {'xx': {0: {'hlp': {'rtrn': 'no'}}}}}}}} result i want display: "b2b": [ {"sat": [ { "somekey": "value", "sat1": [ { "hlp": { "return": "no", "xx": 0, "xx1": 0, "xx2": 0 }, } ] } ] } ] how can i display such result? i want to show the difference between the two dictionaries a and b? -
Which language better to use for server side scripting django or php or node.js what would be result if django vs php vs node.js
Please suggest me for strong webserver interpreter node.js,php,django -
django-cors-headers not working at all
Well, initially I had forgotten the middleware class but after adding it just worked fine ( It was a week ago ). Now, I am back to my workstation and I find it again not working. The ACCESS_CONTROL_ALLOW_ORIGIN headers are not at all being set. I have tried all that is, placing the middleware at top, before CommonMiddleware but it just doesn't work. This is my setting.py file : DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'account', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', ] # if DEBUG: # INSTALLED_APPS += 'corsheaders', # MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware', ] # else: # MIDDLEWARE = [] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = DEBUG This is the response I am getting : Date: Sun, 14 Jan 2018 09:35:09 GMT Server: WSGIServer/0.1 Python/2.7.14+ X-Frame-Options: SAMEORIGIN Content-Type: text/html; charset=utf-8 Content-Length: 146 -
Save Instance Nested Serializers in Django Rest Framework
I have problem with saving instance Live_In Nested Serializers in Django Rest Framework. Hope your guys help me! I think just a basic issue. My Serializers: I think it comes error when I write saving instance class UserEditSerializer(ModelSerializer): live_in = CityLiveInSerializer(many=False) about = serializers.CharField(source='profile.about') class Meta: model = User fields = [ 'username', 'live_in', 'about', ] def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.save() # Update Serializers Profile if (validated_data.get('profile') is not None): profile_data = validated_data.pop('profile') profile = instance.profile profile.about = profile_data.get('about', profile.about) profile.save() if (validated_data.get('live_in') is not None): live_in_data = validated_data.pop('live_in') ins = instance.city.live_in ins.live_in = live_in_data.get('name', ins.live_in) ins.save() return instance My City Model (Live_in) class City(BaseCity): class Meta(BaseCity.Meta): swappable = swapper.swappable_setting('cities', 'City') class BaseCity(Place, SlugModel): name = models.CharField(max_length=200, db_index=True, verbose_name="standard name") country = models.ForeignKey(swapper.get_model_name('cities', 'Country'), related_name='cities') Data sent by Postman (Json) { "live_in": { "name": "Encamp" } } TraceError: Exception Value: Cannot assign "u'Encamp'": "Profile.live_in" must be a "City" instance. File "/Users/lecongtoan/Desktop/FeedTrue/backend/api/authentication/views.py" in edit 43. serializer.save() File "/Users/lecongtoan/Desktop/FeedTrue/backend/api/authentication/serializers.py" in update 185. ins.live_in = live_in_data.get('name', ins.live_in) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py" in set 216. self.field.remote_field.model._meta.object_name, Exception Type: ValueError at /api/v1/users/account/edit/ -
Admin css won't load when deploying Django project on pythonanywhere
So I had some trouble with static files when I tried deploying them... Thing is that I manage to server the main static files and everything is working except for the admin. I think maybe something is wrong with my configuration. Here is screenshot of my web: https://i.imgur.com/RtuStM2.png This is my settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') SECRET_KEY = 'ie&_vj_d)t5itbpun3%58tlw(3=ptn1^5qj43kgm^&_z^!5(' DEBUG = False ALLOWED_HOSTS = ['danielcirstea.pythonanywhere.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rango', 'registration' ] 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', 'django.middleware.locale.LocaleMiddleware' ] ROOT_URLCONF = 'tango_with_django_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR, ], '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.template.context_processors.media' ], }, }, ] WSGI_APPLICATION = 'tango_with_django_project.wsgi.application' LANGUAGE_CODE = 'ro' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [STATIC_DIR, ] STATIC_URL = '/static/' MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' REGISTRATION_OPEN = True ACCOUNT_ACTIVATION_DAYS = 7 REGISTRATION_AUTO_LOGIN = True LOGIN_REDIRECT_URL = '/rango/' LOGIN_URL = '/accounts/login/' -
Django Rest-Framework nested serializer order
Is there a way to order a nested serializer _set, for example order by pk or time-stamp. So basically order song_set shown in the json data below from the most reacent to the latest object created, in this case by order_by('-timestamp') or order_by('-pk'). Json data { "pk": 151, "album_name": "Name", "song_set": [ { pk: 3, timestamp: '5 seconds' }, { pk: 2, timestamp: '10 seconds' }, { pk: 1, timestamp: '15 seconds' } ] } Model class Album(models.Model): album_name = models.CharField(max_length=100, blank=True) class Song(models.Model): album = models.ForeignKey('album.Album', default=1) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) Searilizer class SongListSerializer(HyperlinkedModelSerializer): class Meta: model = Song fields = [ 'pk', 'timestamp' ] class AlbumSerializer(HyperlinkedModelSerializer): song_set = SongListSerializer(many=True, read_only=True) class Meta: model = Album fields = [ 'pk', 'timestamp', 'song_set' ] -
How to display Last name in custom user profile in Django
I need to display the last name of all the user in user profile but I am able to display only the username. Admin.py from django.contrib import admin from commonpage.models import UserProfile,PositionTable #register the above models class user_action(admin.ModelAdmin): list_display = ['user', 'useractive','position','team_name','preferd_shift'] ordering = ['id'] list_filter = ('useractive','position','team_name','preferd_shift') list_editable = ['position','team_name','preferd_shift'] actions = [make_user_active,make_user_deactive] # Register your models here. admin.site.register(UserProfile,user_action) admin.site.register(PositionTable) -
Why can I not customize the style on certain input fields within Django framework?
My issue is simple: my first three input fields are able to be customized and the last three input fields are not. I do not see any discrepancies between the individual input fields. Could someone please spot my (hopefully) overlooked error? Thanks in advance. Note: I am using Bulma as my CSS framework and am specifically using only Bulma's base settings. from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User widgets = { 'username': forms.TextInput(attrs={'class':'input'}), 'first_name': forms.TextInput(attrs={'class':'input'}), 'last_name': forms.TextInput(attrs={'class':'input'}), 'email': forms.TextInput(attrs={'class':'input'}), 'password1': forms.TextInput(attrs={'class':'input'}), 'password2': forms.TextInput(attrs={'class':'input'}) } fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') Below is the HTML: <body> {% include "navbar.html" %} <section class="section"> <div class="container"> <h1 class="is-size-1">Sign up below!</h1> <form id="register_form" class="field" method="POST" action="{% url 'oraclewebsite:register' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="field"> <label for="label">Username</label> <div class="control"> {{form.username}} </div> <label for="label">First Name</label> <div class="control"> {{form.first_name}} </div> <label for="label">Last Name</label> <div class="control"> {{form.last_name}} </div> <label for="label">Email</label> <div class="control"> {{form.email}} </div> <label for="label">Password</label> <div class="control"> {{form.password1}} </div> <label for="label">Re-enter Password</label> <div class="control"> {{form.password2}} </div> </div> <br> <input class="button is-info" type="submit" name="submit" value="Register"/> </form> </div> </section> -
How to display ValidationErrors to users, and not 500s?
I'm having trouble understanding how to display errors to users in Django when DEBUG = FALSE. I'm just learning Django, so I could very well be missing something obvious/simple. One example I'm trying to solve, is when a user is registering and their username/email is already taken, a validation error is presented. I can't seem to get this error to show when debugging is off. Here is my code: registration.html {% block content %} <div class="container"> <div class="row main"> <div class="panel-heading"> <div class="panel-title text-center"> <h1 class="title">My title</h1> <hr /> </div> <div class="main-login main-center"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} <form class="form-horizontal" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> <div class="login-register"> <a href="{% url 'login' %}">Already registered? Login!</a> </div> </form> </div> </div> </div> </div> {% endblock %} views.py def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): userObj = form.cleaned_data first_name = userObj['first_name'] last_name = userObj['last_name'] username = userObj['username'] email = userObj['email'] password = userObj['password'] … -
Django Model - facing error while makemigrations - 'UserSkill.user' is not a foreign key to 'UserProfile'
I am new to Django - ORM and facing issues with creating relations . The db is SQLite . I am trying to solve following problem such that N+1 db problem is not present - A User will add different Skills to his/her profile .S/He can also create new skills which were earlier not present and can add to the profile . Other users can upvote the skills on user profile - this should be recorded in Database too . Uptill not I have created following models but it is giving foreign key error on running makemigrations .Also I figured out this that I need a new class to Map the upvotes of skills by other user on current user profile - for this I am not sure should I create a New class or use existing model class . Error - > SystemCheckError: System check identified some issues: ERRORS: wantedly_webapp.UserProfile.user_skills: (fields.E339) 'UserSkill.user' is not a foreign key to 'UserProfile'. wantedly_webapp.UserSkill: (fields.E336) The model is used as an intermediate model by 'wantedly_webapp.UserProfile.user_skills', but it does not have a foreign key to 'UserProfile' or 'Skill'. #import from django models module from django.db import models # This class will more or less … -
Can't extend user models in Django Admin?
The admin console doesn't show me the UserProfile in Django Admin. There are no errors that show up. I reloaded my server but it still doesn't show in the console. from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=100, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') phone = models.IntegerField(default=0)` admin.py: from django.contrib import admin from account.models import UserProfile admin.site.register(UserProfile)` -
import error during running my server in django project
Unhandled exception in thread started by Traceback (most recent call last): File "/home/kamal/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/kamal/.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/kamal/.local/lib/python2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/home/kamal/.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/kamal/.local/lib/python2.7/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/home/kamal/.local/lib/python2.7/site-packages/django/core/checks/urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "/home/kamal/.local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in get res = instance.dict[self.name] = self.func(instance) File "/home/kamal/.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/kamal/.local/lib/python2.7/site-packages/django/utils/functional.py", line 33, in get res = instance.dict[self.name] = self.func(instance) File "/home/kamal/.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/kamal/Desktop/mywebsite/mywebsite/urls.py", line 17, in from django.urls import path ImportError: No module named urls -
I cannot do a lookup through the foreignkey anymore
I have a model for shops inside shops app class ShopAccount(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) managers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="manager_workers", blank=True) business_name = models.CharField(max_length=200) dashboard_banner_image_1 = models.ImageField(upload_to = upload_location, null = True, blank = True) I have another model inside of bookings app class Booking (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) destination = models.CharField(max_length=200, blank=True, null=True) shop = models.ForeignKey(ShopAccount, null=True, blank=True) booking_date = models.DateTimeField() mobile_contact = models.CharField(max_length=11, blank=True, null=True) inside of bookings app (bookings/views.py) i have this code snippet def booking_create_view(request): if request.method == 'POST': print (request.POST) shop_id = request.POST.get('shop') instance_location_destination = request.POST.get('instance_location_destination') form = BookingForm(request.POST) shop = ShopAccount.objects.get(id=shop_id) print (shop) everything is correct until this point shop = ShopAccount.objects.get(id=shop_id) my code returns an error saying cannot resolve 'id' into fields: Choices are print(shop) returns None to my database