Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - models design issue
I'm struggling designing my models on Django (using PostgreSQL). The goal is to create a system of groups where a user can arrange items in them. An item must be unique in my database. I created a user item group (UserItemGroup) that belong to a user (User). Then, I created an item model (UserItem). This model represents an item which the user can arrange into groups. Items can belong to multiple groups at the same time but must be unique! I used 2 ForeignKey in the UserItem model but it seems very weird... See below: class UserItemGroup(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=False) slug = models.CharField(max_length=200, blank=False, null=False) class UserItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(UserItemGroup, on_delete=models.CASCADE) Items can be arranged like so: user_x ------group_a ------------item_1 ------------item_2 ------------item_3 ------group_b ------------item_1 ------------item_4 Hope I'm clear, thanks in advance for help. -
Why does response content change when I write to a file?
I'm trying to work with XML obtained from http://video.google.com/timedtext that contains closed caption data of YouTube videos. As I'm fairly new to both Django and XML, I tried to directly output the XML - i.e. the response's content to the webpage - as the first step, by passing it directly in the context while rendering it as a 'p' element in the template. This worked fine. The XML displayed as a byte string. I then used the Python module 'xmltodict' to convert the XML to a more workable format. This worked too, but I got an error message: [19/Jan/2021 17:48:07] "GET /_hpvE1jjdxY/ HTTP/1.1" 200 2744 [19/Jan/2021 17:48:09] "GET /favicon.ico HTTP/1.1" 301 0 Internal Server Error: /favicon.ico/ Traceback (most recent call last): File "D:\Dev\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Dev\Project\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Dev\Project\src\lt_player\views.py", line 26, in player parsed_cc_data = xmltodict.parse(cc_data)['transcript']['text'] File "D:\Dev\Project\venv\lib\site-packages\xmltodict.py", line 327, in parse parser.Parse(xml_input, True) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 2, column 11 [19/Jan/2021 17:48:10] "GET /favicon.ico/ HTTP/1.1" 500 75167 I looked up why this error could've popped up and I noticed some reasons such as the placing of a misplaced '&' character or some other … -
Django Conflicts Error When use ManyToManyField
I have two model like given in bellow; class userPages(models.Model): page_name=models.CharField(max_length=30) parent_id=models.IntegerField(blank=True, null=True) def __str__(self): return self.page_name class userProfile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,related_name="profile") user_pages=models.ManyToManyField(userPages) def __str__(self): return self.user.username When I want to add data like this; . . . p1 = userPages(page_name='Login') p1.save() user_profile = userProfile(user=new_user) user_profile.save() user_profile.user_pages.add(p1) I got "syntax error at or near "ON"". LINE 1: ... ("userprofile_id", "userpages_id") VALUES (1, 1) ON CONFLIC... -
Django Paginator - all pages objects action
Folks, I'm currently developing a web application using Django and need to replicate a feature that currently exists in the admin section of Django. Namely, there is an option to select objects on all pages and take same action on all these. I have a Paginator on my page, but not sure what would be the best way to tell the server I want to perform an action on all objects, not only these being currently shown. Please advise! Cheers! -
University Appointment Based System: Django (Backend,sqlite), ReactJS(Frontend)
Hi guys im a university student embarking on a project and need some initial guidance as to the appropriate course of action to take. Basically Im creating an appointment based systems which allows students to book appointments with the teacher. The application must be able to consolidate both their timetables and only highlight the days when both the teacher and student are "free" so that the student can book the consultation slot. Im planing to use Django for backend and reactJS for front end. I just seek initial opinion/direction of as to how i can begin by constructing this system and more importantly what algorithm that I can use to consolidate the timetables of both the teacher and the student so that the system only highlights the duration and date where both parties are free Will greatly appreciate any form of feedback you can provide. Thank You -
Django contact e-mail form does not render/show up in home.html
I have a forms.py - file in the "portfolio" - app with the following content: from django import forms class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) # From docs: https://docs.djangoproject.com/en/3.1/topics/forms/#more-on-fields cc_myself = forms.BooleanField(required=False) In my views.py I have the following relevant part: from .forms import ContactForm # import module from same parent folder as this script import General.Misc.general_tools as tools # custom module to import special-print function def contactView(request, admin_email='blaa@blaaa.com'): if request.method == 'GET': sendemail_form = ContactForm() else: sendemail_form = ContactForm(request.POST) if sendemail_form.is_valid(): # * Retrieve data and set up e-mail (subject, sender, message) subject = sendemail_form.cleaned_data['subject'] from_email = sendemail_form.cleaned_data['from_email'] message = sendemail_form.cleaned_data['message'] # From docs: https://docs.djangoproject.com/en/3.1/topics/forms/#more-on-fields cc_myself = sendemail_form.cleaned_data['cc_myself'] recipients = [admin_email] if cc_myself: recipients.append(from_email) # * Send email try: # General Django docs: https://docs.djangoproject.com/en/3.1/topics/email/#send-mail # NOTE on passed list as 4th parameter: recipient-list ## i) How to set up an email contact form - docs: https://learndjango.com/tutorials/django-email-contact-form send_mail(subject, message, from_email, recipients, fail_silently=False) # * Exceptions * # # NOTE on scope: security except BadHeaderError: return HttpResponse('Invalid header found.') # General exception to be printed out except Exception as e: tools.except_print(f"ERROR:\n{e}") # Return success (if this code is reached) return redirect('success') # Send the completed … -
how to create a multiple database in app? [closed]
We have a research project in school which is a website that store all student informations. And we are currently using django. We would like to make it login by campus location (We need to create an app for many campuses ). What should we do to make the app have a different data inside and will be base by the campus location of the user that login? -
Why is it throwing an Django- Reverse query name SystemCheckError?
I am a newbie to Django, While running the django application using python3 manage.py runserver Because of the way I have created the model I am getting an error like django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: database.LeadsStatus.company_id: (fields.E305) Reverse query name for 'LeadsStatus.company_id' clashes with reverse query name for 'LeadsStatus.companies'. HINT: Add or change a related_name argument to the definition for 'LeadsStatus.company_id' or 'LeadsStatus.companies'. database.Users.id: (fields.E007) Primary keys must not have null=True. HINT: Set null=False on the field, or remove primary_key=True argument. System check identified 2 issues (0 silenced). This is how I've created model. class LeadsStatus(models.Model): id = models.IntegerField(primary_key=True, auto_created=True) company_id = models.ForeignKey('Companies', null=False, db_index=True, on_delete=models.CASCADE) status = models.CharField(max_length=120) users_id = models.IntegerField() assign_date = models.DateTimeField() companies = models.OneToOneField('Companies', on_delete=models.CASCADE) I believe the error might be because of the way I have created a OneToOneField. How do I solve this error. Please help me understand. Thanks -
Unit testing in Django for CreateView
I have a CreateView with which I create new blog posts, I want to test it in order to check if everything is ok but something is wrong with my test and I can't understand what exactly. it gives me 2 errors, for the first method I get this error: Traceback (most recent call last): File "C:\Users\Bularu Lilian\Desktop\EcoMon\blog\tests\test_views.py", line 73, in test_post_create_view_GET self.assertEquals(response.status_code, 200) AssertionError: 302 != 200 and for the second one is this error: File "C:\Users\Bularu Lilian\Desktop\EcoMon\blog\tests\test_views.py", line 78, in test_post_create_view_POST_success post = Post.objects.get(title=self.post['title']) File "C:\Users\Bularu Lilian\Desktop\Environments\ecomon\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Bularu Lilian\Desktop\Environments\ecomon\lib\site-packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( blog.models.Post.DoesNotExist: Post matching query does not exist. This is my Test class: class TestPostCreateViews(BaseTest): def test_post_create_view_GET(self): response = self.client.get(self.add_post_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'blog/add_post.html') def test_post_create_view_POST_success(self): response = self.client.post(self.add_post_url, self.post, author=self.user, format='text/html') post = Post.objects.get(title=self.post['title']) self.assertEquals(response.status_code, 302) self.assertEquals(post.title, 'test post') my CreateView: class PostCreateView(LoginRequiredMixin, IsSuperuserOrStaffMixin, CreateView): template_name = 'blog/add_post.html' form_class = PostCreateForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) my url path: path('new/post/', PostCreateView.as_view(), name='add-post'), my form: class PostCreateForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(), max_length=200) content = forms.CharField(widget=forms.Textarea(attrs={'rows': 25, 'cols': 50})) class Meta: model = Post exclude = ['author', 'slug', 'published_date', 'updated_date'] and my model: class … -
How to redirect to previous page in custom DeleteView?
I have the following custom DeleteView: class CarDeleteView(LoginRequiredMixin, DeleteView): model = Car context_object_name = 'car' template_name = 'cars/car_confirm_delete.html' success_message = "%(name)s is pending removal" def get_success_url(self): return reverse('car-list') def delete(self, request, *args, **kwargs): self.object = self.get_object() name = self.object.name owner = self.object.owner if owner != self.request.user: messages.error(request, f'You don't have permissions to remove {name}') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # DO Stuff return redirect(reverse('car-list')) I'm trying to redirect to previous entry point when user isn't the owner (so he can't delete). But HttpResponseRedirect(request.META.get('HTTP_REFERER')) gives me the URL of the current page (car_confirm_delete.html) and not the previous one. How can I make it go to previous one? -
Deleting a Foreign Key model?
I'm trying to delete a Foreign Key model, however after I delete it and try and save the model I get a ValueError: save() prohibited to prevent data loss due to unsaved related object 'orderassigned'. What I'm trying to achieve is delete the orderassigned Foreign Key model itself. Below is this deletion code in views.py: ordertocancel = Order.objects.get(orderid=orderid, orderassigned__user=self.request.user) ordertocancel.orderassigned.delete() # This references a Foreign Key ordertocancel.status = "ordered" ordertocancel.save() This is the Foreign Key: orderassigned = models.ForeignKey('Assigned', null=True, blank=True, on_delete=SET_DEFAULT, default=None) Any help would be greatly appreciated, thank you! -
I'm getting ModuleNotFoundError: No module named '<anyproject>'
To generate some fake data i used "djnago_populator" as fakers.py and when I run code getting something related to "DJANGO_SETTINGS_MODULE". I searched in stackoverflow regarding this and saw there to use "set DJANGO_SETTINGS_MODULE=admin.settings" and didnt generated fakedata but i ran "set DJANGO_SETTINGS_MODULE=ecom.settings" where ecom is my project name. and so this generated fake data. and now i'm able to runserver command and able to visit localhost. but when I go admin site below error is getting Error at /admin/ Incorrect padding Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 2.1.7 Exception Type: Error Exception Value: Incorrect padding Exception Location: G:\Install\Python 3.8\lib\base64.py in b64decode, line 87 Python Executable: G:\Install\Python 3.8\python.exe Python Version: 3.8.2 Python Path: ['E:\\Workspace\\Atom_Wrksc\\django\\ecom', 'E:\\Workspace\\Atom_Wrksc\\django\\ecom', 'C:\\Program Files\\JetBrains\\PyCharm ' '2020.3.2\\plugins\\python\\helpers\\pycharm_display', 'G:\\Install\\Python 3.8\\python38.zip', 'G:\\Install\\Python 3.8\\DLLs', 'G:\\Install\\Python 3.8\\lib', 'G:\\Install\\Python 3.8', 'G:\\Install\\Python 3.8\\lib\\site-packages', 'G:\\Install\\Python 3.8\\lib\\site-packages\\django_misaka-0.2.1-py3.8.egg', 'G:\\Install\\Python 3.8\\lib\\site-packages\\pygments-2.7.3-py3.8.egg', 'G:\\Install\\Python ' '3.8\\lib\\site-packages\\houdini.py-0.1.0-py3.8-win32.egg', 'C:\\Program Files\\JetBrains\\PyCharm ' '2020.3.2\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Tue, 19 Jan 2021 10:53:17 +0000 Traceback Switch to copy-and-paste view G:\Install\Python 3.8\lib\site-packages\django\contrib\sessions\backends\base.py in _get_session return self._session_cache ... ▶ Local vars During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: G:\Install\Python 3.8\lib\site-packages\django\core\handlers\exception.py in inner i uninstalled django and installed again and tested. but samee error i'm getting. I also started a … -
how to add field to userchangeform?
I have extended the abstract user class but the fields I added is phone number but this field did not appear in user change form how would I add this field to user change form ? -
Django: Modify database object on click using a ListView
I have a ListView that I use to display a list of products. On the right of every product/row, I want a "archive" button that, when clicked-on, will change the "archived" field of the product in the database from True to False. I'd like to do this using only Django and I think this is possible but I have a hard time finding out how. I'm trying to do it using a form, but I don't know how I can send the pk of the current object (in the loop) back to the view to make the change. Here's my template (the relevant part): {% for product in product_list %} <tr> <th scope="row">{{ product.pk }}</th> <td> <a href="{% url 'accounts:products_edit' pk=product.pk %}"> {{ product.title }}</a > </td> <td class="d-flex justify-content-between"> <form action="" method="POST"> {% csrf_token %} <button type="submit"><i class="fas fa-trash" style="color: grey"></i></button> </form> </td> </tr> {% endfor %} Here's my view: class ProductsListView(ListView, LoginRequiredMixin): template_name = "accounts/products/products_list.html" model = Product def get_context_data(self, **kwargs): # ... return context def post(self, request, *args, **kwargs): # modify object from pk here return HttpResponseRedirect(self.request.path_info) I've seen several post with similar situations, but didn't find a solution that works completely for my case. Any help … -
Enumeration types in Django
I am trying to use enumeration types in Django but fell like I am not doing the right thing... I am building an ebay-like webapp where my Listings are saved in the database with a .category attribute. class Listing(models.Model): class Category(models.TextChoices): TOY = "TO", _("Toys") FASHION = "FA", _("Fashion") ELECTRONICS = "EL", _("Electronics") HOME = "HO", _("Home") OTHERS = "OT", _("Others") title = models.CharField(max_length=64) category = models.CharField( max_length=2, choices=Category.choices, default=Category.OTHERS, ) I referred to Django's documentation for the use of Enumeration types but there are some grey areas, as far as my understanding goes. When I render a template to display a Listing, how do I pass the string value associated with the .category of my Listing? I tried something like this: return render(request, "auctions/listing.html", { "listing": listing, "category": Listing.Category[listing.category].label, }) Or can I access it through the "listing" variable? What I would like is for the browser to display Home for a listing with listing.category = "HO". -
Django test database objects
I created custom database migration for creating new user in database like below: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("core", "0179_merge_20210104_1353"), ] db_user_name = 'database_new_user' db_password = 'database_new_user_password' create_db_user = f""" DO $$ BEGIN CREATE ROLE {db_user_name} WITH NOSUPERUSER NOCREATEDB NOCREATEROLE LOGIN PASSWORD '{db_password}'; EXCEPTION WHEN DUPLICATE_OBJECT THEN RAISE NOTICE 'not creating {db_user_name} -- it already exists'; END $$ """ delete_db_user = f""" DROP ROLE IF EXISTS {db_user_name}; """ grant_read_permissions = f""" DO $$ BEGIN GRANT USAGE ON SCHEMA public TO {db_user_name}; GRANT SELECT ON ALL TABLES IN SCHEMA public TO {db_user_name}; END $$ """ revoke_read_permissions = f""" REVOKE USAGE ON SCHEMA public FROM {db_user_name}; REVOKE SELECT on ALL TABLES IN SCHEMA PUBLIC FROM {db_user_name}; """ operations = [ migrations.RunSQL(create_db_user, delete_db_user), migrations.RunSQL(grant_read_permissions, revoke_read_permissions), ] This migration essentially creates new user in database and grant SELECT for all tables. Reverse options revoke permissions and drop user accordingly. Migration is deployed and working as expected. Problem is that when I try to revert (in local machine) this migration by typing: python manage.py migrate core 0179_merge_20210104_1353 Django says: django.db.utils.InternalError: role "database_new_user" cannot be dropped because some objects depend on it I inspected database and saw that django created test_database (when … -
NoReverseMatch error while adding slug in url path
i'm building a blog app in django. In the blog list page after preview of each button i've added Read More link to read the blog in details. I'm trying to add slug in the blog detail page but it gives the NoReverse error. I get this error: This is my urls.py of blog_app and i've included in main project url.py: app_name = 'blog_app' urlpatterns = [ path('', views.BlogList.as_view(), name='blog_list'), path('write/', views.CreateBlog.as_view(), name='create_blog'), path('details/<slug:slug>/', views.blog_details, name='blog_details'), ] This is the views.py: def blog_list(request): return render(request, 'blog_app/blog_list.html', context={}) class BlogList(ListView): context_object_name = 'blogs' model = Blog template_name ='blog_app/blog_list.html' class CreateBlog(LoginRequiredMixin, CreateView): model = Blog template_name = 'blog_app/create_blog.html' fields = ('blog_title', 'blog_content', 'blog_image') def form_valid(self, form): blog_object = form.save(commit=False) blog_object.author = self.request.user title = blog_object.blog_title blog_object.slug = title.replace(' ', '-') + '-' + str(uuid.uuid4()) blog_object.save() return HttpResponseRedirect(reverse('index')) def blog_details(request, slug): blog = Blog.objects.get(slug=slug) return render(request, 'blog_app/blog_details.html', context={'blog':blog}) This is models.py: class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=264, verbose_name='Assign a Title') slug = models.SlugField(max_length=264, unique=True) blog_content = models.TextField(verbose_name="What's on your Mind") blog_image =models.ImageField(upload_to='blog_images', verbose_name="Blog Image") published_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-published_date'] def __str__(self): return self.blog_title This is blog_details.html: {% extends 'base.html' %} {% block title … -
Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4 error in python django
You see I am getting this incredibly weird error related to the no of characters in a string I guess. I am a bit new to django and I have never see such an weird error. I checked a few threads and according to that this is about encoding and decoding something which I really do not know how to resolve. Here is my code: Request Method: GET Request URL: http://127.0.0.1:8000/profiles/myprofile/ Django Version: 2.1.5 Python Version: 3.9.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts', 'profiles'] Installed 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'] Traceback: File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\sessions\backends\base.py" in _get_session 190. return self._session_cache During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\PROJECTS\social\src\profiles\views.py" in my_profile_view 6. profile = Profile.objects.get(user=request.user) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py" in get 390. clone = self.filter(*args, **kwargs) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py" in filter 844. return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py" in _filter_or_exclude 862. clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py" in add_q 1263. clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\aarti\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py" … -
Django register user
Hi i want to connect normal user using UserCreationForm and my own Creation when i post it with button my postgre auth_user and auth_users_register nthing add to database when i click on button my code: forms.py class RegisterForm(ModelForm): class Meta: model = Register fields = ['date_of_birth', 'image_add'] widgets = { 'date_of_birth': DateInput(attrs={'type': 'date'}) } class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] models.py def validate_image(image_add): max_height = 250 max_width = 250 if 250 < max_width or 250 < max_height: raise ValidationError("Height or Width is larger than what is allowed") class Register(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE) date_of_birth = models.DateField( max_length=8, verbose_name="date of birth") image_add = models.ImageField( upload_to="avatars", verbose_name="avatar", validators=[validate_image]) views.py class RegisterPageView(View): def get(self, request): if request.user.is_authenticated: return redirect('/') user_form = CreateUserForm(request.POST) register_form = RegisterForm(request.POST) return render(request, 'register.html', {'user_form': user_form, 'register_form': register_form}) def post(self, request): if request.method == 'POST': user_form = CreateUserForm(request.POST) register_form = RegisterForm(request.POST) if user_form.is_valid() and register_form.is_valid(): user_form.save() register_form.save(commit=False) user = user_form.cleaned_data.get('username') messages.success( request, 'Your account has been registered' + user) return redirect('login') user_form = CreateUserForm() register_form = RegisterForm() context = {'user_form': user_form, 'register_form': register_form} return render(request, 'register.html', context) -
Variation/Fluctuation in SID for the same user in Apache open meetings 5.0.2
I am facing the issue in fetching the SID of user as it keeps on varying whenever there is GET request passed to the appplication. { "serviceResult": { "message": "bfddf0de-fdcc-4804-b355-a8d33ed57a44", "type": "SUCCESS" } } Below link uses REST to get the SID and create room hash, but the SID keeps on varying for the same user whenever the GET request is passed link : https://openmeetings.apache.org/RestAPISample.html Can anyone suggest how this variation can be rectified and how to proceed further to work with other API urls. link : http://evc-cit.info/openmeetings/webapps/openmeetings/docs/RoomService.html -
How to install Cmake on Django Azure webapp?
I'm trying to deploy a Django Webapp on Azure. One of the libraries I need, depends on Cmake, so im getting the error : CMake must be installed to build the following extensions: _dlib_pybind11 Now, in order to install Cmake on the service, I need to make some SH file, or manually insert some "startup" commands, is there a way to "pre-install" Cmake before the install of requirements.txt? -
How do i filter certain items in a model field by id of another model?
This is kind of a weird question class Post(models.Model): name = models.CharField(max_length=200) class PostKey(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) name = models.CharField(max_length=200) def __str__(self): return self.post.name + " | " + self.name I am trying to use the detail view such that it displays the details of the Post model as well as shows a list of PostKey (couldn't think of any other name) which has the same id as post.id. I have created a one to many relation with the Post model using ForeignKey. Here is my view: from django.shortcuts import render from django.views.generic import TemplateView, DetailView from .models import Post, PostKey class TestView(TemplateView): template_name = "test.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["posts"] = Post.objects.all() return context class PostDetailView(DetailView, Post): template_name = "test2.html" model = Post def get_context_data(self, **kwargs ): context = super().get_context_data( **kwargs) context['details'] = PostKey.objects.filter(id= Post.id) return context but when I run this code it shows me something like this: TypeError at /post/2 Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x03F88478>. I have tried to add int(Post.id) but it still doesn't work. Here are is the template that is getting rendered for the above view. {% for detail in details %} {{detail.name}} {% endfor … -
django celery asynchronous file saves to storage
So I want to asynchronously conduct file saves to django file storage. I've tried to achieve this by overwriting the default File System Storage class. import hashlib import os import uuid import django.core.files.storage as storage from celery import shared_task from django.core.files import File class DefaultStorage(storage.FileSystemStorage): def __init__(self): super(DefaultStorage, self).__init__() @shared_task def _save(self, name, content): # need to encrypt file before saving return super(DefaultStorage, self)._save(name, content) @shared_task def _open(self, name, mode='rb'): # need to decrypt before opening return File(open(self.path(name), mode)) def get_available_name(self, name, max_length=None): # we return a hash of the file given, # in case we miss out on uniqueness, django calls # the get_alternative_name method dir_name, file_name = os.path.split(name) file_root, file_ext = os.path.splitext(file_name) file_root = hashlib.md5(file_root.encode()).hexdigest() name = os.path.join(dir_name, file_root + file_ext) return super(DefaultStorage, self).get_available_name(name, max_length) def get_alternative_name(self, file_root, file_ext): # we insert a random uuid hex string into the given # file name before returning the same back return '%s%s%s' % (file_root, uuid.uuid4().hex, file_ext) def save(self, name, content, max_length=None): # override existing system storage save method # to ensure that we call the shared task and # utilize the distributed task queue celery offers has_chunks = hasattr(content, 'chunks') name = content.name if not name else name content = … -
How to overwrite Django app to Pythonanywhere? 3
After the second time deploying the Django app to Pythonanywhere, (I re-edited and overwritten in VS code and did git push) I got the following error. The command is pa_autoconfigure_django.py https://github.com/[user_name]/[project_name].git --nuke Is that something exceeded? What should I delete? I don't know what wrong it is... Downloading llvmlite-0.33.0-cp36-cp36m-manylinux1_x86_64.whl (18.3 MB) |███████████████████████████▍ | 15.7 MB 14.7 MB/s eta 0:00:01ERROR: Could not install packages due to an EnvironmentError: [Errno 122] Disk quota exceeded Traceback (most recent call last): File "/home/hogehoge/.local/bin/pa_autoconfigure_django.py", line 47, in <module> main(arguments['<git-repo-url>'], arguments['--domain'], arguments['--python'], nuke=arguments.get('--nuke')) File "/home/hogehoge/.local/bin/pa_autoconfigure_django.py", line 31, in main project.create_virtualenv(nuke=nuke) File "/home/hogehoge/.local/lib/python3.6/site-packages/pythonanywhere/django_project.py", line 29, in create_virtualenv self.virtualenv.pip_install(packages) File "/home/hogehoge/.local/lib/python3.6/site-packages/pythonanywhere/virtualenvs.py", line 28, in pip_install subprocess.check_call(commands) File "/usr/lib/python3.6/subprocess.py", line 311, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['/home/hogehoge/.virtualenvs/hogehoge.pythonanywhere.com/bin/pip', 'install', '-r', '/home/hogehoge.pythonanywhere.com/requirements.txt']' returned non-zero ex it status 1. -
Django Sent Mail work in localhost but not in host server Cpanel
I make a e-commerce Website. When i run it on my localhost, Django sent mail can sent mail properly. But after hosting it, sent mail does not happend. It can not sent email. Settings.py #Email Settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'email' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL= 'Team <Team@support>' Views.py: send_mail( 'Purchase Order', # subject 'email_for_buy', # massage '', # from email ['email'], # to email fail_silently=True, ) Can someone help me, how can i able to sent email by django sent email from my cpanel host