Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError at /students/exam/1/ int() argument must be a string, a bytes-like object or a number, not 'list'
I am trying to submit this form through this model and views which I am getting this error. Though, I want to also submitenter image description here it to the database. I have taking al my value just to drop it into database. I will be very happy if you should assist to solve the save() method as well. student.py @login_required @student_required def take_exam(request, pk): course = get_object_or_404(Course, pk=pk) student = request.user.student question = course.questions.filter() #correct_answers = student.course_answers.filter(answer__question__quiz=course, answer__is_correct=True).count() total_questions = course.questions.count() choice = Answer.objects.filter() marks_obtainable = Details.objects.get(course_id=course) if request.method == 'POST': question_pk = request.POST.getlist('question_pk') question_obj = Question.objects.filter(id=int(question_pk)) choice_pk = [request.POST['choice_pk{}'.format(q)] for q in question_obj] #print(marks_obtainable.marks_obtained) zipped = zip(question_obj, choice_pk) for x, y in zipped: correct_answers = Answer.objects.filter(question_id=x, is_correct=True).values("id").first()['id'] print(x, y, correct_answers) if int(y) == int(correct_answers): #z = TakenQuiz(student=student, course=course, \ #question=x, selected_choice=y, marks_obtained=marks_obtainable, is_correct=True) print("correct") else: print("Not Correct") return render(request, 'classroom/students/take_exam_form.html', { 'course': course, 'question': question, 'course': course, 'total_questions': total_questions, 'choice': choice, 'marks_obtainable': marks_obtainable }) models.py class Question(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='questions') text = models.CharField('Question', max_length=500) def __str__(self): return self.text class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') text = models.CharField('Answer', max_length=255) is_correct = models.BooleanField('Correct answer', default=False) def __str__(self): return self.text take_exam_form.html <h2 class="mb-3">{{ course.name }}</h2> Course id <h2 … -
In Django when extending AbstractUser, how do you reorder admin fields?
In a Django app I have a class that extends AbstractUser: class CustomUser(AbstractUser): uid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ...more fields that are not in the parent... When I look at the /admin/ I see that the parent fields are on top, and it looks really bad, with the password being the first field. How do I put the child fields on top? -
user data is saving to database but employerform data not saving
Models.py class EmployerUser(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User,on_delete=models.CASCADE) company_name = models.CharField(max_length=20,default="") address = models.TextField(default="") industry = models.CharField(choices=INDUSTRY,max_length=20,default="") isSalarySacrifies = models.CharField(max_length=20,choices=SALARYSACRIFIES,default=False) isNetpayRelief = models.CharField(max_length=20,choices=NETPAY,default=False) contribution_type = models.CharField(choices=CONTRI_TYPE,max_length=20,default="") contribution_change_type = models.CharField(choices=CONTRI_CHANGE_TYPE,max_length=20,default="") payrise_type = models.CharField(choices=PAYRISE,max_length=20,default="") bonus_type = models.CharField(choices=BONUS,max_length=20,default="") def __str__(self): return self.company_name views.py def register_view(request): form = UserRegisterForm(request.POST or None) profileform = EmployerUserForm(request.POST or None) if form.is_valid() and profileform.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get('password') user.set_password(password) user.save() profile = profileform.save(commit=False) profile.save() # messages.success(self.request, 'Register Successfully') return redirect('login') context = { 'form': form, 'profileform': profileform, } return render(request, "registration/signup.html", context) forms.py: UserRegisterForm class UserRegisterForm(forms.ModelForm): first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'First Name'})) last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Last Name'})) email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) mobile = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Mobile'})) class Meta: model = User fields = [ 'first_name', 'last_name', 'mobile', 'email', 'password' ] def clean(self, *args, **kwargs): email = self.cleaned_data.get('email') email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError( "This email has already been registered") return super(UserRegisterForm, self).clean(*args, **kwargs) EmployerUserForm class EmployerUserForm(ModelForm): company_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Company Name'})) address = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Address'})) industry = forms.ChoiceField(choices = INDUSTRY,widget=forms.Select()) isSalarySacrifies = forms.ChoiceField(choices=SALARYSACRIFIES,widget=forms.RadioSelect()) isNetpayRelief = forms.ChoiceField(widget=forms.RadioSelect(),choices=NETPAY) contribution_type = forms.ChoiceField(label="Contribution Type",choices = CONTRI_TYPE,widget=forms.Select()) contribution_change_type = forms.ChoiceField(label="Contribution Change Rate Type",choices = CONTRI_CHANGE_TYPE,widget=forms.Select()) payrise_type = forms.ChoiceField(label="Payrise",choices = PAYRISE,widget=forms.Select()) bonus_type = forms.ChoiceField(label="Bonus",choices = BONUS,widget=forms.Select()) class Meta: … -
Django Form is not Showing when clicking button
I am trying to add new data(certificate data) in my database with the help of form in Django. for that i am made a button(new certificate ) when i click on that button form is supposed to popup so that user can enter detail of new certificate but (new certificate)button is not working, I don't know where i am going wrong , maybe i am not giving right URL in app-> url.py . please help i am putting all detail below along with images. website(project)-> url.py urlpatterns = [ path('admin/', admin.site.urls), path('music/', include('music.urls')),] music(App) -> url.py urlpatterns=[ path('',views.index, name = 'index'), path('basic',views.basic, name = 'basic'), path('saveIncident',views.saveIncident, name = 'saveIncident'), path('DisplayIncident',views.DisplayIncident, name = 'DisplayIncident'), path('login',views.login, name = 'login'), url(r'^list/$', views.list, name='list'), url(r'^list/create$', views.certificate_create, name='certificate_create'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) model.py class certificateData(models.Model): Dev = 1 QA = 2 UAT = 3 Production = 4 environment_TYPES = ( (Dev, 'Dev'), (QA, 'QA'), (UAT, 'UAT'), (Production, 'production'), ) application = models.CharField(db_column='Application', primary_key=True, max_length=255, blank=True, null=False) # Field name made lowercase. startdate = models.DateField(null=True) expiredate = models.DateField(null=True) environment_type = models.PositiveSmallIntegerField(choices=environment_TYPES) list.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Certificate</title> <link href="{% … -
Django TemplateDoesNotExist problem while DIR is correctly set
I was running this Django project perfectly previously using Python3.7.2 and Django 2.1.5, recently I installed Anaconda3 and changed the interpreter to the Python3.7.1 in it. After reinstalling Django, when I ran the project the TemplateDoesNotExist exception showed up. My OS is Windows 10. My DIRS is set as below: TDIR = os.path.join(BASE_DIR, 'Templates/').replace('\\', '/') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TDIR], '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', ], }, }, ] This note is on the error page: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\admin\templates\welcomePage.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\auth\templates\welcomePage.html (Source does not exist) It seems that Django search the Anaconda path for templates instead of the customized path, but I can see on the error page that it was correctly set. This is what the error page shows: TEMPLATES [{'APP_DIRS': True, 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['D:/IgnorazWork/SUDoc/SUDoc/Templates/'], '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']}}] And'D:/IgnorazWork/SUDoc/SUDoc/Templates/'is exactly where I put the templates. How does this happen? Thanks! -
ValueError when creating Django comment form
I have a problem when I was creating the comment form by django. After I done with my view.py, models.py and html, I got an ValueError said "Cannot assign "": "Comment.post" must be a "post" instance". Below are my codes. HTML {% block content %} <h1>Add New Comment:</h1> <form method='POST' action=''> {% csrf_token %} {{ form.as_p }} <button type='submit'>Submit</button> </form> {% endblock %} views.py def add_comment(request, slug): po = get_object_or_404(post, slug=slug) if request.method == 'POST': form = CommentForm(request.POST or None) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('blog:post', slug=post.slug) else: form = CommentForm() return render(request, 'blog/post/add_comment.html', {'form': form}) models.py class Comment(models.Model): post = models.ForeignKey(post, related_name='comments', on_delete=models.CASCADE) user = models.CharField(max_length=250) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) def approved(self): self.approved = True self.save() def __str__(self): return self.user -
Display table view of RAW print output - Django
I have a raw output from a print function which looks something like the below: b'\r\nsw-dektec#\r\nsw-dektec#terminal length 0\r\nsw-dektec#sh mvr members\r\nMVR Group IP Status Member Membership \r\n-------------------------------------------------------------\r\n232.235.000.001 ACTIVE/UP Gi1/0/21 Dynamic \r\n232.235.000.002 ACTIVE/UP Gi1/0/21 Dynamic \r\n232.235.000.003 ACTIVE/UP Gi1/0/21 Dynamic I want to parse the above txt and only display 232.235.000.x when i click a button on my webpage. And am checking if we can display the output in the below format: Multicast IP ------------ 232.235.000.001 232.235.000.002 232.235.000.003 Here is my view.py so far: if 'RETRIEVE' in request.POST: remote_conn_pre = paramiko.SSHClient() remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) remote_conn_pre.connect(hostname='172.31.255.4', port=22, username='admin', password='******', look_for_keys=False, allow_agent=False) remote_conn = remote_conn_pre.invoke_shell() remote_conn.send("\n") remote_conn.send("terminal length 0\n") remote_conn.send("sh mvr members\n") time.sleep(1) iptv = remote_conn.recv(65535) print (iptv) for line in iptv: remote_conn.send("end\n") remote_conn.send("exit\n") -
Subprocess in Django 2.1.7
So, my problem is pretty straight forward I want to execute the following shell command in Django 2.1.7 libreoffice --headless --convert-to "txt:Text (encoded):UTF8" test.doc More info. I will be uploading a Doc file and want to convert it to txt. I was thinking if i could use the libreoffice to do so. My server is Ubuntu 18.04 with Python 3.6.7 I would be uploading the file in Media Root for now and then i would like to start the conversion. Up till now I have tried to do the following: @api_view(['POST']) def convertfiledoc(request): file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(file.name, file) uploaded_file_url = 'media/' r = subprocess.call("libreoffice --headless --convert-to" +"txt:Text (encoded):UTF8" + "test.doc ") print(r) return Response(data={"message": uploaded_file_url}, status=status.HTTP_200_OK) Error is as follows FileNotFoundError: [Errno 2] No such file or directory: 'libreoffice --headless --convert-totxt:Text (encoded):UTF8test.doc ': 'libreoffice --headless --convert-totxt:Text (encoded):UTF8test.doc ' I know that the function I have written is not complete but I was trying to do it to see if it works properly. I even tried to hardcode the file but no success. -
Run coverage test in a docker container
I am trying to use the coverage tool to measure the code coverage of my Django app, when i test it work fine, but when i pushed to github, i got some errors in travis-ci: Traceback (most recent call last): File "/usr/local/bin/coverage", line 10, in <module> sys.exit(main()) File "/usr/local/lib/python3.6/site-packages/coverage/cmdline.py", line 756, in main status = CoverageScript().command_line(argv) File "/usr/local/lib/python3.6/site-packages/coverage/cmdline.py", line 491, in command_line return self.do_run(options, args) File "/usr/local/lib/python3.6/site-packages/coverage/cmdline.py", line 641, in do_run self.coverage.save() File "/usr/local/lib/python3.6/site-packages/coverage/control.py", line 782, in save self.data_files.write(self.data, suffix=self.data_suffix) File "/usr/local/lib/python3.6/site-packages/coverage/data.py", line 680, in write data.write_file(filename) File "/usr/local/lib/python3.6/site-packages/coverage/data.py", line 467, in write_file with open(filename, 'w') as fdata: PermissionError: [Errno 13] Permission denied: '/backend/.coverage' The command "docker-compose run backend sh -c "coverage run manage.py test"" exited with 1. my travis.yml: language: python python: - "3.6" services: - docker before_script: pip install docker-compose script: - docker-compose run backend sh -c "python manage.py test && flake8" - docker-compose run backend sh -c "coverage run manage.py test" after_success: - coveralls and my dockerfile FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 # Install dependencies COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client jpeg-dev RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev musl-dev zlib zlib-dev RUN pip install -r /requirements.txt RUN apk … -
Django - Signal.disconnect does not disconnects the signal
I can't figure out why disconnect of post_save signal does not work in my project. When I call PipedriveSync.objects.first().sync_with_pipedrive(), it does something and then tries to save some information to the object. Then, the sync_pipedrivesync receiver is called which calls sync_with_pipedrive() again which invokes sync_pipedrivesync etc etc. To avoid this cycling I've created two methods - disconnect_sync and connect_sync which should disconnect signal when saving instance and then revoke it. But it doesn't work. I can see in debugger that the last line in sync_with_pipedrive - self.save(disconnect=True) invokes the signal. Do you know what is wrong? models.py class PipedriveSync(TimeStampedModel): pipedrive_id = models.IntegerField(null=True, blank=True) last_sync = models.DateTimeField(null=True, blank=True) last_sync_response = JSONField(null=True, blank=True) last_sync_success = models.NullBooleanField() last_backsync = models.DateTimeField(null=True, blank=True) last_backsync_response = JSONField(null=True, blank=True) last_backsync_success = models.NullBooleanField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def save(self,disconnect=True,**kwargs): if disconnect: PipedriveSync.disconnect_sync() super().save(**kwargs) PipedriveSync.connect_sync() @classmethod def disconnect_sync(cls): post_save.disconnect(sync_pipedrivesync) @classmethod def connect_sync(cls): post_save.connect(sync_pipedrivesync,sender=PipedriveSync) def sync_with_pipedrive(self): if self.pipedrive_id: action = 'update' else: action = 'create' relative_url = self.build_endpoint_relative_url(action) payload = self.get_serializer_class()(self.content_object).data response = None if action == 'create': response = PipeDriveWrapper.post(relative_url, payload=payload) if response['success']: self.pipedrive_id = response['data']['id'] if action == 'update': response = PipeDriveWrapper.put(relative_url, payload=payload) try: success = response['success'] except KeyError: success = … -
TypeError: create_superuser() missing 3 required positional arguments:
Got the following error when I try to create new superuser using terminal. TypeError: create_superuser() missing 3 required positional arguments: 'first_name', 'last_name', and 'location' I followed another stackoverflow page , in comments below. first_name , last_name and location are CharField with max_length = 30 and it can have blank values. In this custom-user-model the username is replaced with mobile_no by making it as unique in the User class. models.py from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager,PermissionsMixin ) class UserManager(BaseUserManager): # All required field must be passed below as argument def create_user(self, mobile_no, role, email, first_name, last_name, location, password=None, is_active=True,is_staff=False, is_admin= False): if not mobile_no: raise ValueError("User must have an Mobile number as username ") if not password: raise ValueError("Users must have a password") user_obj= self.model( mobile_no= mobile_no ) user_obj.email = email user_obj.set_password(password) user_obj.role = role user_obj.first_name = first_name user_obj.las_name = last_name user_obj.is_active = is_active user_obj.location = location user_obj.is_staff = is_staff user_obj.save(using=self._db) return user_obj def create_superuser(self, mobile_no, role, email, first_name, last_name, location, password=None, is_active=True,is_staff=False, is_admin= False): user_obj= self.model( mobile_no=mobile_no ) user_obj.email = email user_obj.set_password(password) user_obj.role = role user_obj.first_name = first_name user_obj.las_name = last_name user_obj.location = location user_obj.is_staff = True user_obj.is_admin = True user_obj.is_active = is_active user_obj.save(using=self._db) return user_obj … -
local variable 'sql' referenced before assignment
Hi im trying to write a function using if/elif , i'm having trouble when trying to execute the final cursor function after the elif. I think my indent is wrong and i been trying to find where the mistake at over a day now : def api_report(request): params = request.GET if params["type"] == 'revenue': sql = get_revenue_query(params) elif params["type"] == 'order_count': sql = get_order_created_count(params) elif params["type"] == 'product_count': sql = get_product_count(params) elif params["type"] == 'order_card_created_count': sql = get_order_card_created_count(params) elif params["type"] == 'product_count': sql = get_product_count(params) elif params["type"] == 'card': sql = get_card_query(params) elif params["type"] == 'order_not_card_created_count': sql = get_order_not_card_created_count(params) elif params["type"] == 'product': get_product_report(request) elif params["type"] == 'order_rate_by_district': sql = get_order_rate_by_district(params) with connection.cursor() as cursor: cursor.execute(sql) rows = cursor.fetchall() data = [] for row in rows: data.append(OrderRateDataEntry(row[0], row[1], row[2])) serializer = OrderRateDataEntrySerializer(data, many=True) return JsonResponse(serializer.data, safe=False) pass with connection.cursor() as cursor: cursor.execute(sql) rows = cursor.fetchall() data = [] for row in rows: data.append(TimeSeriesDataEntry(row[0], row[1])) serializer = TimeSeriesDataEntrySerializer(data, many=True) return JsonResponse(serializer.data, safe=False) here the error cursor.execute(sql) UnboundLocalError: local variable 'sql' referenced before assignment the "elif params["type"] == 'product':" and "elif params["type"] == 'order_rate_by_district':" have they own function to execute, i want the other conditions to jump to the last cursor function … -
Could not spawn process for application deploying Django on Cpanel
I'm given this domain name on NameCheap with the server. Now I design Django app and trying to deploy on the server but I had problems [ E 2019-03-19 06:23:19.7356 598863/T2n age/Cor/App/Implementation.cpp:221 ]: Could not spawn process for application /home/username/IOT: The application process exited prematurely. App 644163 output: File "/home/username/IOT/passenger_wsgi.py", line 1, in <module> App 644163 output: File "/home/username/virtualenv/IOT/3.7/lib64/python3.7/imp.py", line 171, in load_source this is my passenger_wsgi.py: from myproject.wsgi import application I had tried several tutorials: https://www.youtube.com/watch?v=ffqMZ5IcmSY&ab_channel=iFastNetLtd.InternetServices https://smartlazycoding.com/django-tutorial/deploy-a-django-website-to-a2-hosting https://hostpresto.com/community/tutorials/how-to-setup-a-python-django-website-on-hostpresto/ https://www.helloworldhost.com/knowledgebase/9/Deploy-Django-App-on-cPanel-HelloWorldHost.html https://www.helloworldhost.com/knowledgebase/9/Deploy-Django-App-on-cPanel-HelloWorldHost.html how to install django on cpanel Very much applicate if you could help -
Get m2m field(with through model) list in django
I'm using Django 2.0.7. I want to get all the filed of a model.I can get all the normal fields in : model._mata.fields And I can get m2m fields in: model._meta.local_many_to_many However,if the m2m fields has an through table, I can't access them?how can i achieve this? -
I'm creating a webhook(Http callbacks). I have to convert my code using Django rest framework from Django standard code
This is code which I'm using in Django standard code https://medium.com/@raiderrobert/how-to-make-a-webhook-receiver-in-django-1ce260f4efff please refer to this for further information -
Django - accessing values in multiple databases
I need to make sure that an object (Device) is only saved once and only to one database. I have several PostGre SQL databases as so: List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -------------------------------+-------+----------+------------+------------+------------------- admin | admin | UTF8 | en_US.utf8 | en_US.utf8 | postgres | admin | UTF8 | en_US.utf8 | en_US.utf8 | reference | admin | UTF8 | en_US.utf8 | en_US.utf8 | template0 | admin | UTF8 | en_US.utf8 | en_US.utf8 | =c/admin + | | | | | admin=CTc/admin template1 | admin | UTF8 | en_US.utf8 | en_US.utf8 | =c/admin + | | | | | admin=CTc/admin workspace_A | admin | UTF8 | en_US.utf8 | en_US.utf8 | workspace_B | admin | UTF8 | en_US.utf8 | en_US.utf8 | workspace_C | admin | UTF8 | en_US.utf8 | en_US.utf8 | workspace_D | admin | UTF8 | en_US.utf8 | en_US.utf8 | Workspaces A,B,C and D all have a table called devices_device which contains an ID, a name and some other fields. What function(s) do I need to call when saving a Device (over-writing the Django save() function) to make sure that a Device with the same parameters is not already present? -
Get list of Users and comment made by them (Django Serializers)
Have Users Table (with fields id, name) and Comments Table (Comment, CreatedBy (integer) - which is user id). How can i write a serialiser to fetch the list of users, that should contain the array of comments created by each user. class UserSerializer(serializers.ModelSerializer): class Meta: model = Users fields = ('id','name') class CommentSerializer(serializers.ModelSerializer): class Meta: model = UserComments fields = ('id','comment','created_by') -
How to do in operation in django
class ModelA(models.Model): f = models.CharField(max_length=50) class ModelB(models.Model): a = ForeignKey(ModelA) b = models.CharField(max_length=50) I want to get f in model A and I know b . How can I do this by using django orm ? -
Having a good streaming experience
I am working on a project which involves uploading and streaming of videos by learners.The videos are hosted in the same server where my application is hosted. My project is based on django, videojs and mysql. I am using nginx to serve the contents. My problem is the streaming experience is not very good. The video stalls after every few seconds. What are some things I can do to enhance the streaming. I am aware I should be hosting the videos with service providers such as vimeo but for now I just want to host the videos locally. Any advice are welcomed. -
One-way delete delete Django Channels thread
I'm trying to make it possible for users to delete a thread with another user from their inbox. I've followed the Django Docs DeleteView although this may be totally wrong. views.py class ThreadDeleteView(DeleteView): model = Thread success_url = reverse_lazy('inbox') models.py class ThreadManager(models.Manager): def by_user(self, user): qlookup = Q(first=user) | Q(second=user) qlookup2 = Q(first=user) & Q(second=user) qs = self.get_queryset().filter(qlookup).exclude(qlookup2).distinct() return qs # method to grab the thread for the 2 users def get_or_new(self, user, other_username): # get_or_create username = user.username if username == other_username: return None # looks based off of either username qlookup1 = Q(first__username=username) & Q(second__username=other_username) qlookup2 = Q(first__username=other_username) & Q(second__username=username) qs = self.get_queryset().filter(qlookup1 | qlookup2).distinct() if qs.count() == 1: return qs.first(), False elif qs.count() > 1: return qs.order_by('timestamp').first(), False else: Klass = user.__class__ user2 = Klass.objects.get(username=other_username) if user != user2: obj = self.model( first=user, second=user2 ) obj.save() return obj, True return None, False class Thread(models.Model): first = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_first') second = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_second') updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = ThreadManager() def __str__(self): return f'{self.id}' @property def room_group_name(self): return f'chat_{self.id}' def broadcast(self, msg=None): if msg is not None: broadcast_msg_to_chat(msg, group_name=self.room_group_name, user='admin') return True return False html thread page with delete button <!-- Delete Thread --> … -
Django: Add new foreign key to existing model with default value as another foreign key from the same model
I recently started using Django, so please be patient. I have a model with 2 foreign keys class Application(models.Model): assessment_owner = models.ForeignKey(User, related_name='assessment_owner') creator = models.ForeignKey(User, related_name='creator') I am trying to add new foreign key called tech_lead to the same model, and default value for tech_lead should be assessment_owner. Later on, I can update the value for tech_lead using data load, but initially it should be assessment owner. With following code snippet, Django asks for a default value while making migrations and assigns the same tech_lead everywhere. I would like to define default value for tech_lead through code, and simple default attribute doesn't work. I have tried using signals pre_save and post_save with no luck. class Application(models.Model): assessment_owner = models.ForeignKey(User, related_name='assessment_owner') creator = models.ForeignKey(User, related_name='creator') tech_lead = models.ForeignKey(User, related_name='tech_lead') I am using Django 1.11.3 and postgreSQL. Thanks in advance. -
Jquery, Django, Infinite Scroll load rest of elements after page is loaded
I was able to implement infinite scrolling into my Django website's home page following this guide: https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html Basically the Jquery code that triggers the infinite scroll is this (plus some django code): <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0] }); </script> This is good because I load the page pretty quickly and the user is then able to infinite scroll as the other elements load. What I want to achieve now is to load the page like I do now and immediately after, without the need of scrolling down, I want to load the rest of the elements. So basically load the page with the first few elements and then load all the remaining elements without having to scroll. Note that I have used the above guide's implementation as it is a convenient way of being able to use all of Django's power (especially related to foreign keys), so I am trying to stick to this approach. Is there a way to do so changing the what the Jquery is triggered only? Thanks, Vittorio -
TypeError at /post/3/comment/ 'dict' object is not callable
class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) text = models.TextField() image = models.ImageField(upload_to='Comment_Pictures', blank=True) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.text def get_absolute_url(self): return '/' class CommentAddView(LoginRequiredMixin, CreateView): model = Comment fields = ['text', 'image'] def form_valid(self, form): form.instance.author = self.request.user form.instance.post = Post.objects.get(id=self.kwargs['pk']) return super().form_valid(form) TypeError at /post/3/comment/ 'dict' object is not callable Request Method: POST Request URL: http://localhost:8000/post/3/comment/ Django Version: 2.1.7 Exception Type: TypeError Exception Value: 'dict' object is not callable -
Django, postgres: IntegrityError null value in column, but column should accept null
I have this model: Class Job(models.Model): // Some fields slug = models.SlugField(verbose_name=_("slug"), max_length=151, null=True, blank=True) def get_absolute_url(self): return reverse("jobs", kwargs={"slug": self.slug}) Slug should accept Null value. And it does. For example, I create this on the shell, and it works ok: In [1]: j = Job.objects.create(title="my faked title",date_start=aware_start, date_end=aware_end, amount_to_pay=10, email='fake@gmail.com') In [2]: j Out[2]: <Job: my faked title> But if I want to test it, on a test case, it fails. The test case is: class JobCreationTest(TestCase): def test_simple_creation(self): import datetime import pytz aware_start = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC) aware_end = datetime.datetime(2012, 8, 15, 8, 15, 12, 0, pytz.UTC) Job.objects.create(title="my faked title",date_start=aware_start, date_end=aware_end, amount_to_pay=10, email='fake@gmail.com') And the error trace is: self = <django.db.backends.utils.CursorWrapper object at 0x7fc2bc72af28> sql = 'INSERT INTO "posts_job" ("id", "created_at", "created_by_id", "updated_at", "updated_by_id", "deleted", "title", "ema...slug") VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)' params = (UUID('e814e054-e273-4316-b670-f39584f0b3ef'), datetime.datetime(2019, 3, 19, 9, 39, 31, 31514, tzinfo=<UTC>), None, datetime.datetime(2019, 3, 19, 9, 39, 31, 31566, tzinfo=<UTC>), None, False, ...) ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0x7fc2d0486f28>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x7fc2bc72af28>}) def _execute(self, sql, … -
navigation bar which contains a link which redirect to a frame in django
</script> <div class='nav'> <ul> {% for li in th_coun_li %} <li><a href="#" onclick=Myfunction({{li}})>Thread Dump {{li}}</a></li><br> {% endfor %} </ul> </div></div><div id="frame"></div> <script> function Myfunction(li){ src1="<iframe src='{% url 'threadcount1' li %}' width='2000' height='1000';> </iframe>"; document.getElementById('frame').innerHTML = src1 ; } I am trying to make a nav bar when that nav bar links are clicked then it will open an i frame but it is giving me this error Reverse for 'threadcount1' with arguments '('',)' not found. 1 pattern(s) tried: ['mainpage/analysis/threadcount/(?P[0-9]+)$']