Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to insert into django model with foreign key pointing to user model
I am pretty new to django and I am working on a job portal website. My users are recruiters and students. When a recruiter posts a job, i am able to retrieve all the values from the form but unable to insert in my Internship Model. Can you guys help please? Here is my code: models.py class Recruiter(models.Model): STATUS_CHOICES = ( ('Pending', 'Pending'), ('Accepted', 'Accepted'), ) user = models.ForeignKey(User,on_delete=models.CASCADE) position = models.CharField(max_length=50) status = models.CharField(max_length=20, choices=STATUS_CHOICES) user_type = models.CharField(max_length=10, choices=USER_TYPE_CHOICES) def __str__(self): return self.user.username class Internship(models.Model): recruiter = models.ForeignKey(Recruiter, on_delete=models.SET_NULL, null=True) internship_title = models.CharField(max_length=100) internship_desc = RichTextField() start_date = models.DateField() end_date = models.DateField() posted_date = models.DateField() def __str__(self): return self.internship_title views.py def post_internship(request): if not request.user.is_authenticated: messages.warning(request,"Please login first") return redirect('login') if request.method == 'POST': start_date = request.POST['start_date'] end_date = request.POST['end_date'] internship_title = request.POST['internship_title'] internship_desc = request.POST['internship_desc'] user = request.user recruiter = Recruiter.objects.get(user=user) try: Internship.objects.create(recruiter=recruiter, internship_title=internship_title, internship_desc=internship_desc, start_date=start_date, end_date=end_date, posted_date=date.today()) except: print('error') return render(request, 'post_internship.html', context) -
remove registred celery tasks from drop down menu django admin
I have several registred tasks. Сan I not show some of them? For example, so that the drop-down menu does not have main.tasks._start_proxy_loading -
In django template when scrolling remove div blocks
In django template (queryset) when scrolling remove div blocks as soon as they disappear from the browser's field of view, i.e. dynamically when scrolling down, delete blocks from the top, when scrolling up, delete blocks from the bottom and when need to re-display them? (Sorry for my English) -
Handle static and media files on django develop and production environment
I'm trying to understand how static and media files have to be handled on Django in Development and production environment. On development I have a folder called "media" where, for example, user's images are stored. My settings.py and urls.py, looks like this and works fine: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,"media") urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My question is regarding to production environment. I want that media files (After run collectstatic) to be saved on another folder (/api/vol/media) on the production server. Should I have another settings.py for my production environment? Or how should I handle this? Thanks a lot -
Django testing - subclassing tests and project directory structure
I am developing a django app, and for the first time, I want to do so, using TDD. This is my directory structure: /myproject manage.py /app1 models.py views.py urls.py /tests test_models.py test_forms.py test_views.py /myproject settings.py # ... etc. /tests __init__.py functional_tests.py base.py visitor.py loggedin.py member.py functional_tests.py import unittest from visitor import VisitorTest from loggedin import LoggedInTest from member import SpecialMemberTest if __name__ == '__main__': unittest.main() base.py import os from pathlib import Path from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import unittest # https://stackoverflow.com/questions/1323455/python-unit-test-with-base-and-sub-class class BaseTestCases: class BaseTest(unittest.TestCase): def get_browser(self, is_headless=False): chrome_options = webdriver.ChromeOptions() chrome_options.headless = is_headless chrome_options.add_argument("--disable-notifications") chrome_options.add_argument(f"user-data-dir={str(Path.home())}") # https://stackoverflow.com/questions/31062789/how-to-load-default-pro chrome_options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36") browser = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options) return browser def setUp(self): self.browser = self.get_browser() def tearDown(self): self.browser.quit() def test_common(self): pass logedin.py from base import BaseTestCases class LoggedInTest(BaseTestCases.BaseTest): pass member.py from base import BaseTestCases class SpecialMemberTest(BaseTestCases.BaseTest): pass visitor.py from base import BaseTestCases class VisitorTest(BaseTestCases.BaseTest): def test_can_start_a_list_and_retrieve_it_later(self): # Edith has heard about a cool new online to-do app. She goes # to check out its homepage self.browser.get('http://localhost:8000') # She notices the page title and header mention to-do lists self.assertIn('To-Do', self.browser.title) self.fail('Finish the test!') # She is invited to enter a to-do … -
Show field only once after created Django admin
I'm trying to create an implementation of API Keys for my API, so the Externals can request an API Key and they will have access to my resources. Right now I'm using the Django admin to show and create these API Keys class External(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) name = models.CharField(max_length=255, null=False, blank=False) is_enabled = models.BooleanField(default=True) revenue_percentage = models.FloatField() created = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class ApiToken(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) name = models.CharField(max_length=255, null=False, blank=False) external = models.ForeignKey(External, on_delete=models.CASCADE) token_hash = models.CharField(max_length=128) token = models.CharField(max_length=128) created = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): if self._state.adding: # In order to know if it's being created api_key = get_random_string(length=32) concat = f'{self.id}:{api_key}' key_bytes = concat.encode('ascii') base = base64.b64encode(key_bytes) token = base.decode('ascii') self.token = token self.token_hash = make_password(api_key) super(ApiToken, self).save(*args, **kwargs) and this is the admin class ApiTokenAdmin(admin.TabularInline): model = ApiToken extra = 0 fields = ('id', 'name', 'token', 'created') readonly_fields = ('created', 'token') exclude = ('id',) class ExternalAdmin(admin.ModelAdmin): search_fields = ('id', 'name',) list_display = ('id', 'name', 'revenue_percentage', 'is_enabled',) list_filter = ('is_enabled',) fields = ('id', 'name', 'is_enabled', 'revenue_percentage') readonly_fields = ('id', 'created') inlines = [ApiTokenAdmin] admin.site.register(External, ExternalAdmin) As you see I'm storing the token that I want to share self.token = token … -
how to get logged in user data(username) in the models.py file of different app in django?
My django project has two apps - home App and models App. Home App is responsible for creating users(signup and login) into database. models App is responsible for predicting heart disease of user and storing disease result. My problem is I want to create a database in models app and want to retrieve the logged in user data in models App database. -
copying to STATIC_ROOT using collectstatic but image not visible
Need to access static files from common directory as suggested in https://docs.djangoproject.com/en/3.2/ref/contrib/staticfiles/ command, python manage.py collectstatic copies to STATIC_ROOT but when referring to it in html, it throws error Not Found: /static/teststatic/images/product-5.jpg How to make it work with files from the STATIC_ROOT location ? I have tried this and has worked <img src="{% static 'teststatic/static/teststatic/images/product-5.jpg' %}" alt="Trulli" width="500" height="333"> urls.py from django.urls import path from . import views app_name = 'teststatic' urlpatterns = [ path('tstatic/', views.tstatic, name='tstatic'), ] views.py from django.shortcuts import render # Create your views here. def tstatic(request): return render(request, 'tstatic.html', {}) settings.py . . STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_DIRS = ( ('testcss', os.path.join(BASE_DIR, 'testcss', 'static', 'testcss')), ('helpdesk', os.path.join(BASE_DIR, 'helpdesk', 'static', 'helpdesk')), ('teststatic', os.path.join(BASE_DIR, 'teststatic', 'static', 'teststatic')), (os.path.join(BASE_DIR, 'staticfiles')) ) STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' tstatic.html {% load staticfiles %} <!DOCTYPE html> <html> <body> <h2>HTML Image</h2> <img src="{% static 'teststatic/images/product-5.jpg' %}" alt="Trulli" width="500" height="333"> </body> </html> Error : 2021-04-27 12:42:47,744: Not Found: /static/teststatic/images/product-5.jpg -
save method in django views.py not working after overriding it in models,py
this is my home function from views.py file, I am trying to update the count of comments on respective blogs if anyone have commented on my blog post. everything was working fine before but then I added save method in models.py and from then even if i change keywords of blog from admin panel and tries to save it , it saves but don't update the keywords and keeps the previous one. [ i printed every blog and their respective comments and they are printing the right result suppose my blog 1 had 2 comments and someone added new comment i get three as comment count for blog 1 ] Can someone please tell me what's the issue and help me to solve it. def home(request): all_blogs = Blog.objects.all() for b in all_blogs: comment_per_blog = Comment.objects.filter(blog=b.id, active=True).count() print(f"blog {b.id} has {comment_per_blog} comment") b.blog_comments = comment_per_blog b.save() This is my blog model from the models.py file. class Blog(models.Model): objects = models.Manager() slug = models.SlugField(default="", null=True, blank=True, max_length=255) keywords = models.CharField(max_length=500, default="", null=True, blank=True) title = models.CharField(max_length=500) main_image = models.ImageField(upload_to='Blog', null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) body = RichTextUploadingField(null=True, blank=True) tags = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) likes = … -
Not authenticating in DRF
I want to log in using email and password. But the authentification is not happening. have a look at the codes. class LoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=50) password = serializers.CharField(max_length=50) def validate(self, data): email = data.get("email") password = data.get("password") if email and password: user = authenticate(username=email, password=password) print(user) if user: data['user'] = user print(user.id) else: msg = 'login failed' raise exceptions.ValidationError(msg) else: msg = 'provide credientials' raise exceptions.ValidationError(msg) return data views. class LoginView(APIView): def post(self, request): serializer = TokenObtainSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] djangologin(request, user) token, created = Token.objects.get_or_create(user=user) return Response({'message':'You have successfully Logged in.','user':user.id,'token': token.key}, status=200) -
Winerror8 while installing Django 3.2
I was trying to install Django 3.2 using pip.The installation was completed 50% but suddenly an error popup showing [winerror8] not enough storage can someone help me with this. -
JsonResponse data isn't sent to template
i'm learning to use ajax with django this is the resault {"post": "[{\"model\": \"app.post\", \"pk\": 37, \"fields\": {\"author\": 2, \"updated_dt\": \"2021-04-27T14:22:07.811Z\", \"content\": \"Second Post\", \"created_dt\": \"2021-04-27T14:22:07.677Z\", \"status\": 0, \"page\": null, \"group\": null, \"photo\": \"\", \"video\": \"\", \"likes\": [], \"love\": [], \"sad\": [], \"wow\": [], \"haha\": [], \"angry\": []}}]"} i don't know what seems to be the problem that's my views : def AddPostView(request): content = request.POST.get('content') pic = request.FILES.get('photo') vid = request.FILES.get('video') author = request.user post = Post.objects.create(author=author, photo=pic, video=vid, content=content) post.save() name = request.user.first_name.capitalize() + " " + request.user.last_name.capitalize() data = serializers.serialize('json', [ post, ]) return JsonResponse({"post": data}, status=200) that's the ajax code url = '{% url 'add-post' %}' $("#posts-submit").click(function () { $.ajaxSetup({ headers: { "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value, } }); $.ajax({ url: url, method: 'POST', dataType: 'json', success: function (data) { $("#posts-container").appendToUsrTable(data.html_form); } }); }); -
Django: Try reverse of model's __str__() function
I want a function that can have the reverse result of the model __str__ function. For example I have: Model class DepartmentModel(models.Model): department_name = models.CharField(max_length=100) department_description = models.CharField(max_length=500) def __str__(self): return self.department_name As part of the Custom Field TypedModelListField I need to convert the models string representation into an object if it exists. Say I have object <DepartmentModel: Finance> which called __str__() returns "Finance" I'd like to take string "Finance" and have the effects of reversing the __str__() function to return the object <DepartmentModel: Finance> if possible. Form class AddDepartment(forms.Form): user = CustomFields.TypedModelListField( queryset=DepartmentModel.objects.all()) Custom Field class TypedModelListField(forms.ModelChoiceField): def to_python(self, value): if value == '' or value == None: raise forms.ValidationError('Entry cannot be empty') ##################################################################### ### HERE I WANT TO TRY AND CONVERT __STR__ REPRESENTATION to OBJ ### ##################################################################### value = super().to_python(value) return value class ListTextWidget(forms.TextInput): def __init__(self, dataset, name, *args, **kwargs): super().__init__(*args) self._name = name self._list = dataset self.attrs.update({'list':'list__%s' % self._name,'style': 'width:100px;'}) if 'width' in kwargs: width = kwargs['width'] self.attrs.update({'style': 'width:{}px;'.format(width)}) if 'identifier' in kwargs: self.attrs.update({'id':kwargs['identifier']}) def render(self, name, value, attrs=None, renderer=None): text_html = super().render(name, value, attrs=attrs) data_list = '<datalist id="list__%s">' % self._name for item in self._list: data_list += '<option value="%s">' % item data_list += '</datalist>' return (text_html + … -
IntegrityError at /job/create/ NOT NULL constraint failed: core_job.category_id
I'm creaating an api that user can create a job. when I want to test it with postman and create a job I have this error: IntegrityError at /job/create/ NOT NULL constraint failed: core_job.category_id how do i can fix it ?? models: class Category(models.Model): name = models.CharField(max_length=300) slug = models.SlugField(max_length=300, unique=True, help_text='write in English.') sub_category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) class Job(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=400, unique=True) slug = models.SlugField(max_length=400, unique=True, allow_unicode=True) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) image_1 = models.ImageField(upload_to='products_pic/%Y/%m/%d/', null=True, blank=True) description = models.TextField(null=True, blank=True) phone1 = models.CharField(max_length=12, null=True, blank=True) phone2 = models.CharField(max_length=12, null=True, blank=True) phase = models.CharField(max_length=1, null=True, blank=True) address = models.TextField(null=True, blank=True) daily_start_work_time = models.TimeField(null=True, blank=True) daily_end_work_time = models.TimeField(null=True, blank=True) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) popular = models.BooleanField(default=False) views: class JobCreateView(generics.CreateAPIView): permission_classes = (IsAuthenticated,) serializer_class = JobSerializer queryset = Job.objects.all() -
Django development server restarts when changing template (HTML) files
I started a new project in Django 3.2. Unlike what I am used to, on my development machine the runserver restarts automatically when I change template files (HTML files). I am not used to this happening - normally these would always be loaded from disk and changes did not require a restart. A restart is fast but not instantaneous and I rather have the old behavior. I checked the changelog and the runserver documentation but I am not sure if this really is a recent change, or a setting, or if I am overlooking something. Anyone any idea? Below the output of the server in my docker container where you can see that a change to an HTML file triggers the restart... web_1 | /src/templates/_nav.html changed, reloading. web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | April 27, 2021 - 14:16:17 web_1 | Django version 3.2, using settings 'demo.settings' web_1 | Starting development server at http://0.0.0.0:8000/ web_1 | Quit the server with CONTROL-C. -
What is views.py for?
I am currently learning how to build a backend and I have not once stumbled upon the views.py file. Almost everything is happening in my models.py or admin.py file. Is that a problem? What even is views.py for? -
How to user Supervisord with django-background-task module
I am running several background process using django-background-tasks module https://django-background-tasks.readthedocs.io/en/latest/.I am using nohup command for running these 3 queues. can anyone tell me me exactly how to setup http://supervisord.org/ in django to run these background tasks. Thanks in advance. @background(queue='bcp') def process1(): ........ @background(queue='acp') def process2(): ........ @background(queue='fcp') def process3(): ........ -
Dynamically adding cron task on digitalocean with django
I am trying to add a cronjob on DigitalOcean, I've set up Cron by following this tutorial I want to add my cron task lines through Django code, something like file_object = open('/tmp/crontab.UmBDmC/crontab', 'a') file_object.write('* * * * * curl https://mydomain/someurl/') file_object.close() But I can't locate the crontab.UmBDmC folder, every time I run crontab -e I get a different folder name containing crontab file How can I add and remove lines from this file programatically? Any help would be appreciated. -
Django formsets vs writable nested serializers of REST API + JS Framework
I am learning Django since 5 months and I came to a situation where I have to decide if continue learning: Either go in deep with the django formsets (https://docs.djangoproject.com/en/3.1/topics/forms/formsets/) Or start with writable nested serializers of REST API + JS Framework (Angular, I like they wy it is organized). (https://www.django-rest-framework.org/api-guide/relations/#nested-relationships) What do you guys think it is more robust? I suppose the second one but maybe you have more to tell. Thank you very much :) -
Field 'id' expected a number but got <Salary: : - Claude maniragaba>
I want to enable edit when hr state of change is approved def has_change_permission(self, request, obj=None): salary = Salary.objects.filter(id=obj).first() if obj.hr_state == 'request-change-approved' and request.user.user_role.position.code == 'HRM': return True else: return False -
Will there be any style changes when we run a Django project with localhost:8000 and 127.0.0.1:8000?
I tried running server using localhost:8000 and 127.0.0.1:8000 and I noticed that font size is different in both. I couldn't figure out the reason .Fontsize Difference -
how to convert the sql statement to annotate statement
SELECT substr(json_extract(f_test,'$.field_summary.age'), instr(json_extract(f_test,'$.field_summary.age'),'->')+5) AS summary FROM table name; How can I add the sql statement in the objects.annotate(sql)? I succeeded in getting the desired result value with the sql statement, but now this conditional statement is needed for filtering on the object. It is not a simple phrase (ex: select * from school;), but I will contact you I could not find it by googling -
how many fields can be in a django model?
I see some issues in my database while updating my model in Django. it only shows 12 fields! when I added one more field to it and then run makemigrations command, it does not show any changes. I'm using MySQL database init. is there anything in the Django model like we can only define some fields or we can define as much as we need? -
TemplateDoesNotExist at /messages/inbox/ pinax/messages/inbox.html
The Template is present but somehow it wont get located. What could be the problem? -
Django Google AllAuth Site matching query does not exist error on login
I have a Django app I'm trying to deploy on Heroku. Currently, it is deployed to csproject-justin.herokuapp.com . You can find the entire code at https://github.com/travelingaries/Django-Simple-Reservation-App The problem is, when I click on the login button at the top right corner and then press 'Sign in with Google', it throws DoesNotExist at /accounts/google/login/ SocialApp matching query does not exist. I've tried measures suggested on other StackOverflow threads, but none seems to work. When I try to change the Site_ID, it throws an error on the page that shows the Google Sign In button instead(it says 'DoesNotExist at /accounts/login'), so I'm not sure which one's correct. If anyone can help with this issue, I'd greatly appreciate it! Thanks in advance