Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Openedx login query/page shows Page not found when using custom theme
Hi Im using Openedx KOA version. My Problem is when Im using the default theme login page is working. but when I use custom theme Login Page display Page not found. Ive already tried just copying the default header of the default theme but even with just that, login page not found. Ive already modified lms.yml to ENABLE_COMPREHENSIVE_THEMING: true, and set the path to my custom theme. Everything else seems to be working except login page -
How to show a Many-to-Many field in my django HTML Template?
I have one many to many field in my model.py class jira(models.Model): Jira_ID = models.CharField(max_length=100, blank=True) Jira_Story = models.CharField(max_length=500) Short_Description = models.CharField(max_length=500) Story_Points = models.CharField(max_length=30) Sprint = models.CharField(max_length=200) DX4C_Object = models.CharField(max_length=500) Developer = models.ManyToManyField(developer) Sandbox = models.ForeignKey(environments, on_delete=models.CASCADE, limit_choices_to={'Mainline': None},blank=True, null=True) def developer_assigned(self): return ",".join([str(p) for p in self.Developer.all()]) here's my admin.py @admin.register(jira) # class ImpExp(ImportExportModelAdmin): # pass class JiraAdmin(admin.ModelAdmin): list_display = ('id', 'Jira_ID' ,'Jira_Story', 'Short_Description', 'Story_Points', 'Sprint','DX4C_Object','Sandbox', 'developer_assigned') here's my template for that field {% for rt in JIRA %} <td>{{rt.Developer.all}} </td> {% endfor %} in that case i'm getting data as a queryset. But i want data as list. How to achieve that ? -
Series of error and there Fixes in Django if you are working in VS-CODE
problem:1 You might stuck in the configuring the first app in the which gives the a ERROR OF CANNOT IMPORT THE URLS OF YOUR FILE while running in the server. FIX: syntax error : V-S CODE recommend the urlpatterns in CAPS NOT with (s) inside your app please use the correct syntax to run your first app properly . problem:2 you might stuck along with above problem as : thrown django.core.exceptions.ImproperlyConfigured: The included URLconf 'sparta.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. FIX: This is probably cause along with above problem and a simple fix could you have not not added the app in the setting.py of the root directory INSTALLED_APP GOOD LUCK i WILL KEEP FIXING ISSUES DO GIVE IT UPVOTE -
how to do calculation and show on website using Django
I have a project on Hotel Booking Website. I have to create a website like Trivago using Django. When the customer searches the hotel rooms after giving check-in check-out dates and the number of persons, I need to show the price for each hotel on the website. Suppose Hotel1 has a price of 500/ person per day and Hotel2 has 800/person per day. I need to show on that webpage, these 2 available hotels with their final price on the right. The final price is calculated as Final Price= (number of days stayed)*(number of people). Do I need to use models and/or do calculations in views.py Please do tell me how to do this. P.S.- I don't have advanced knowledge of Django, so please suggest a simple approach and complete detail. Thank You very much.Here is the code of the webpage where I want to show -
How to construct django channels group name based on users location
I'm working on location based twitter-like app. Users are supposed to only see and send posts to other users within 10km radius of their location. Using the code below to filter posts it worked very well. def get_queryset(self): user = self.request.user user_coords = user.location.coords user_location = Point(user_coords[0], user_coords[1]) queryset = Post.objects.filter(location__distance_lt=(user_location, Distance(km=10))) return queryset Now I want to make users see posts in realtime. I am using websocket with Django Channels 3.0.3 for realtime. def connect(self): self.group_name = 'posts' # This is just a placeholder # Join group async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() # Sends message to group def send_post(self, message): async_to_sync(self.channel_layer.group_send)( self.group_name, { 'type': 'post', 'message': message, } ) Now I need a way to dynamically group users based on their location so that only users within 10km of each other can get the broadcast from the websocket. I need something like self.group_name = '10km radius of user' -
how to use ForeignKey in django view function
Pack1 - 10$ Pack2 - 40$ Pack3 - 100$ If I select pack2, in case I upgrade my pack I need to show to the output is👇 Pack1 -10$ - disable Pack2 -40$ - disable Pack3 - 60$ -
Trigger specific python function in API based on GET request
Right now, I have two servers; webpage and compute. The webpage consists of a Django application and compute should do all the heavy lifting such that we don't waste resources on webpage and reduces the performance. I'm thinking about making compute an API, where webpage sends requests to, and retrieves from. An example would be: #webpage import requests data = requests.get("https://my_api.com/my_func") # do something with data #compute def my_func(): data = pd.read_sql("SELECT * FROM database") return data def get_func_to_call(request): if request.data=="my_func" return my_func else: return 404 I'm fairly new to APIs, thus I'm searching for suggestions, tutorials, books on how to create an API that would accomplish it. -
How to map ForeignKey Relationship Django for 3 Models
I am planning write one query to get data using 3 models. Modle 1: Emp class Emp(models.Model): empID = models.AutoField(primary_key=True) empName = models.CharField(max_length=70, blank=False, default='') empCode = models.CharField(max_length=10, blank=False, default='') empDesc = models.CharField(max_length=200) class Meta: db_table = 'empolyee' def __str__(self): return self.empName Model 2: Dep class Dep(models.Model): depID = models.ForeignKey(primary_key=True) depName = models.CharField(max_length=200) Emp = models.ForeignKey(EMP, on_delete=models.CASCADE, null=True) class Meta: db_table = 'departmen Model 3: account class Account(models.Model): accountID = models.AutoField(primary_key=True) accountName = models.CharField(max_length=200) Emp = models.ForeignKey(Emp, on_delete=models.CASCADE, null=True) field = models.ForeignKey(Dep, on_delete=models.CASCADE, null=True) class Meta: db_table = 'accounts' I Need execute below native query (SQL): select em.empName as fromMaster, em1.empName as toMaster from dep dp join emp em on dp.depID = em.empID join account ac on dp.depID = ac.field join emp em1 on ac.empID = em1.empID where dep.empID ='1' But I tried with below example but I am getting differnet query. dataReceived = account.objects.select_related( 'field __Emp ', 'Emp ').filter(Emp='1') Could you please help me any one, how to achive this. Thanks in advance !!!! -
Django: ERROR: Command errored out with exit status 1:
I tried to download chatterbox and it started showing error while installing. Then I tried to download django-visits then it showed the same following error: (django_gs) C:\gsData\Workspace\venv\django_gs\src>pip install django-visits Collecting django-visits Using cached django-visits-0.1.6.tar.gz (7.3 kB) Collecting distribute Using cached distribute-0.7.3.zip (145 kB) ERROR: Command errored out with exit status 1: command: 'C:\gsData\Workspace\venv\django_gs\Scripts\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\pc\\AppData\\Local\\Temp\\pip-install-wjigmtsi\\distribute_5b4d0ce4a799441984df2e08779f375e\\setup.py'"'"'; __file__='"'"'C:\\Users\\pc\\AppData\\Local\\Temp\\pip-install-wjigmtsi\\distribute_5b4d0ce4a799441984df2e08779f375e\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\pc\AppData\Local\Temp\pip-pip-egg-info-vg0ihtkz' cwd: C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\ Complete output (20 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\setuptools\__init__.py", line 2, in <module> from setuptools.extension import Extension, Library File "C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\setuptools\extension.py", line 5, in <module> from setuptools.dist import _get_unpatched File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "C:\gsData\Workspace\venv\django_gs\lib\site-packages\_virtualenv.py", line 89, in exec_module old(module) File "C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\setuptools\dist.py", line 7, in <module> from setuptools.command.install import install File "C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\setuptools\command\__init__.py", line 8, in <module> from setuptools.command import install_scripts File "C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\setuptools\command\install_scripts.py", line 3, in <module> from pkg_resources import Distribution, PathMetadata, ensure_directory File "C:\Users\pc\AppData\Local\Temp\pip-install-wjigmtsi\distribute_5b4d0ce4a799441984df2e08779f375e\pkg_resources.py", line 1518, in <module> register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider) AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' ---------------------------------------- WARNING: Discarding … -
Django ValueError (The view views.save_flow_data didn't return an HttpResponse object. It returned None instead.)
When I try to submit my form I get this message: The view views.save_flow_data didn't return an HttpResponse object. It returned None instead. I have to say I'm really starting to regret using Django for this project. I've slimmed down everything so it's easier for you to read. Views.py def save_flow_data(request): if request.method == 'POST': if request.POST.get('upload_flow') \ and request.POST.get('water_flow_rate')\ and request.POST.get('water_flow_rate_unit')\ data=CalcData() data.water_flow_rate = request.POST.get('water_flow_rate') data.water_flow_rate_unit = request.POST.get('water_flow_rate_unit') data.save() return render(request, 'io/flow.html') else: return render(request,'io/flow.html') models.py class CalcData(models.Model): upload_flow = models.BooleanField(default=False) water_flow_rate = models.DecimalField(max_digits=100, decimal_places=5) water_flow_rate_unit = models.TextChoices('wfr_unit', 'm3/day m3/month') datetime = models.DateTimeField(default=timezone.now) submit button in form <div> <button action="{% url 'MyProject:save_flow_data' %}" type="submit" class="btn btn-light" style="width: 517.5px;" >Calculate</button> </div> urls.py urlpatterns = [ path('', views.home, name='MyProject-home'), path('io/flow/', views.io_flow, name='MyProject-io-flow'), path('io/flow/save_flow_data', views.save_flow_data, name='save_flow_data') ] I'm really not sure where to go from here. I had a perfectly working form but as soon as I scaled it up it flopped. -
Getting User Model from Django rest framework Token Authentication token endpoint URL
I want to get all User Model object of user from Token. Token should be on URL which shows all user details like username, first_name, last_name, email. -
How to keep Django CKeditor format on Ionic template
I would like to keep the format set on Django CKeditor plugin. On Django works well because in database i can see the content for this attribute: database column: <p style="text-align:right">Esta es un descripci&oacute;n lo suficientemente larga para poder ver la alineaci&oacute;n del texto en el plugin de ckeditor.</p> And after API request keeps works well: ionic ts file: console.log(this.place.information); <p style="text-align:right">Esta es un descripci&oacute;n lo suficientemente larga para poder ver la alineaci&oacute;n del texto en el plugin de ckeditor.</p> But in the Ionic template not keeps the alignment <div [innerHTML]="place.information"></div> Anybody could help me please ? Thanks in advance -
Sequence of arguments in django signals
Below is the receiver function that I wrote. @receiver(post_save,sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) Is there a specific sequence for the arguments in this function? Can I change the positioning of these arguments? Eg - def create_profile(sender, created, instance, **kwargs) -
Django - How do I save a file from a server locally, and use it on frontend (In production)
I'm building functionality in Django that requires that I download file-data (bytes of png, pdf etc.) from the web. From here I need to save it into a folder, and use it in the frontend by linking to it, like I would with a png-logo from the static folder. This needs to be done while the project in running in production, so a user can click on a button, which then runs a views function that downloads the file into the right folder, and returns a template containing the file (So for example returning : <img src='the downloaded file'>) I've gotten this to work running the code locally by writing a file into my projects static folder, however this doesn't work in production because, to my understanding, a django project in production doesn't use each projects static files. Instead it runs the collectstatic command which collects all static files into one folder. I've therefore written the following code which should save my downloaded files into this static folder: #From function download_file(request) in views.py #file_name, downloaded_bytes are both defined previously. #Define path for saving files into path = f'{settings.BASE_DIR}/static/files/folder1/folder2/' + file_name #Make folders for saving files into try: os.mkdir(f'{settings.BASE_DIR}/static/files/folder1') except OSError … -
Django AuthenticationForm Customization
I am relatively new to django and want to customize the AuthenticationForm but an not sure how to do it. I essentially want to override the init function to be able to inject attributes and control what is displayed on the form. Specifically I would like to add this for my login form: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget = forms.widgets.TextInput(attrs={ 'class': 'form-control' }) self.fields['password1'].widget = forms.widgets.PasswordInput(attrs={ 'class': 'form-control' }) My issue is that I let django do all of the work for me when creating my login view/form therefore I am unsure how to customize it. Reading the docs the LoginView uses the default AuthenticationForm. Any help is greatly appreciated! -
django + ngnix, serving media files
i show you directly my code: i handle the link ewayApp/media/{stuff} with django: urls.py: path('ewayApp/media/<str:media_url_1>/<str:media_url_2>/<str:media_url_3>',course.getMedia), the handler: course.py: def getMedia(request, media_url_1, media_url_2, media_url_3): ...some stuff... url = '/protected/' + media_url_1+'/'+media_url_2+'/'+media_url_3 response['X-Accel-Redirect'] = url return response and i'm sure going for the first link i pass through this function because i have some prints along the function. my ngnix settings: location ~ / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://127.0.0.1:8080; } location ^~ /protected/ { internal; alias path/to/media/media/; } So, the django server runs on 127.0.0.1:8080 and ngnix proxies all the requests there. when accessing these media files if i go straight to the link https://website.com/ewayApp/media/{stuff} ngnix returns me back 404 error not found. I checked if the media are stored in path/to/media/media/, and they are, but obviously in subdirectories with media_url_1, media_url_1 ... that are specified in {stuff} How to solve this? Thanks in advance. -
Django Ajax file upload with progressbar
I'm working on a project where I want to add a progress bar with AJAX when uploading a file. until now I did this but it's not working. I'm using S3 bucket to store the images. models.py class post(models.Model): image = models.ImageField(upload_to='post_pics', null=True, blank=True) content = models.TextField() def __str__(self): return self.content My forms.py class UploadForm(forms.ModelForm): class Meta: model = post fields = ('image', 'content',) My views.py def home_view(request): form = UploadForm(request.POST or None, request.FILES or None) if request.is_ajax(): if form.is_valid(): form.save() return JsonResponse({'message': 'hell yeah'}) context = { 'form': form, } return render(request, 'blog/upload.html', context) My urls.py from django.urls import path from blog.views import home_view urlpatterns = [ path('post/upload/', home_view, name="upload"), ] My upload.html <div id="alert-box"></div> <div id="image-box"></div> <br> <form action="" id="upload-form"> {% csrf_token %} {{form.as_p}} </form> <br> <div id="progress-box" class="not-visible">progress</div> <div id="cancel-box" class="not-visible"> <button id="cancel-btn" class="btn btn-danger">cancel</button> </div> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script> <script> console.log('hello world') const uploadForm = document.getElementById('upload-form') const input = document.getElementById('id_image') console.log(input) const alertBox = document.getElementById('alert-box') const imageBox = document.getElementById('image-box') const progressBox = document.getElementById('progress-box') const cancelBox = document.getElementById('cancel-box') const cancelBtn = document.getElementById('cancel-btn') const csrf = document.getElementsByName('csrfmiddlewaretoken') input.addEventListener('change', ()=>{ progressBox.classList.remove('not-visible') cancelBox.classList.remove('not-visible') const img_data = input.files[0] const url = URL.createObjectURL(img_data) console.log(img_data) const fd = new FormData() fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('image', img_data) $.ajax({ … -
Convert any file format to pdf and store in database as pdf version using python- django
models.py: ----------- class File(models.Model): file = models.FileField( upload_to='documents/%Y/%m/%d', null=True, blank=True, verbose_name=_('file') ) pdf_file_version = models.FileField( upload_to='pdf_documents/%Y/%m/%d', null=True, blank=True, verbose_name=_('pdf file version') ) signals.py ------------- @receiver(post_save, sender=File) def create_pdf_file_version(sender,instance,created,**kwargs): if created: initial_path = instance.file.path print(initial_path) year = time.strftime('%Y') month = time.strftime('%m') day = time.strftime('%d') new_name = '/'.join(['pdf_documents', year, month, day,os.path.basename(initial_path).split('.')[0] + '.pdf']) new_path = os.path.join(settings.MEDIA_ROOT, 'pdf_documents', year, month, day, os.path.basename(initial_path).split('.')[0] + '.pdf') if not os.path.exists(os.path.dirname(new_path)): os.makedirs(os.path.dirname(new_path)) shutil.copy2(initial_path, new_path) output = pypandoc.convert_file(initial_path, 'pdf', outputfile=new_name) instance.pdf_file_version = new_name instance.save() here,I need get uploaded file ,and needs to convert any format to pdf directly without reading it.and save in database as pdf_file_version separately.I must maintain original version and pdf version -
Django: How not to reload the entire page on just a few content updates?
I am using Django as my Web Framework. I want to update the content of a page when the user clicks a button. Is it possible to not update the entire page? For example, if I wanted to program a todo list. Then I would not want to reload the whole page when adding an item at the bottom. Is there a solution for just updating the updatet elements? In my example code below it is unfortunately so that the entire page is reloaded every time def test(request): if request.method == 'POST': context = { 'results': 'Some kind of result', } return render(request, 'users/register.html', context) return render(request, 'users/register.html') -
Dynamic periodic tasks - alternatives to Celery beat
If one wants to set up dynamic and standard periodic tasks scheduling and in a Django project, are there any stable alternatives to celery and celery beat? (when I say dynamic I mean such thing as described here) Would Dramatiq or any other schedulers, for instance, allow for such customization as dynamic user-launched schedulling of periodic tasks? Or are there any other strategies for creating some kind of dynamic schedule with periodic tasks for Django in general ? -
How to view django database on sqliteonline
I want my database deployed on sqliteonline instead of django admin but i am stuck at how to do that. Thanks in advance. It will be of much help! -
Django Models: Automatic field 'modelname_id' is generated
I have been working with from past few month. I saw a weird thing. I have two model like via one to one relationship. one is a core user model and second one is specific user detail model. when i got an attribute error i found an unknown field and when i added it to the admin site in list display i just confused. see my models below models.py class DocsAppointUserModel(AbstractBaseUser,PermissionsMixin): type_choices = ( ('M', 'Moderator'), ('D', 'Doctor'), ('P', 'Patient'), ('A', 'Admin'), ('AS','Admin Staff'), ) first_name = models.CharField(verbose_name="First Name",default="",max_length=30) last_name = models.CharField(verbose_name="Last Name",default="",max_length=30) user_type = models.CharField(verbose_name="User Type",max_length=2,choices=type_choices,default='P') user_email = models.EmailField(verbose_name="Email",max_length=50,primary_key=True) joined_on = models.DateTimeField(auto_now_add=True) last_active_on = models.DateTimeField(auto_now=True) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) #staff for site admin USERNAME_FIELD = 'user_email' #for logging it with email REQUIRED_FIELDS = ["first_name","last_name","user_type"] objects = UserManager() def has_perm(self,perm,obj=None): #returns true if the user has specified permission , # print(perm,obj) if self.is_superuser: return True else: if perm in self.get_user_permissions(): return True else: return False def has_module_perms(self,app_Label): # return true if any user has permission for a perticular module(app) given if self.is_superuser: return True else: all_perm = list(self.get_user_permissions()) for i in all_perm: if i.split('.')[0]==app_Label: return True else: return False def __str__(self): return f'{self.user_email}' def get_full_name(self): … -
I want to send js Array in django
the error it throws is 'NoneType' object has no attribute 'split' . But if i remove first line in script $("#btn").click(function() { ............"except in between ajax code" .............. }); then it runs perfectely why this happens i dont know. <script> $("#btn").click(function() { $.ajax({ method: 'GET', url: '/food_output', data: {'list': list.join(",")}, success: function (data) { alert("worked"); console.log(list); }, error: function (data) { alert("not work"); console.log(list); } }); }); </script> in vews.py def food_output(request): lists = request.GET.get('list') lists =lists.split(',') print(lists) return render(request, "food_output.html") -
Getting Error while deleting Cart item using DestroyAPIView with Javascript. (Django)
I'm using DestroyAPIView with Javascript to delete the cart item in Django While clicking on delete button it shows the following error on chrome console: jquery.min.js:2 DELETE http://127.0.0.1:8000/showdata/2342; 404 (Not Found) send @ jquery.min.js:2 ajax @ jquery.min.js:2 destoryCart @ (index):46 onclick @ (index):1 (index):55 {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} and in vs code terminal showing: Not Found: /showdata/2342; and all my code goes here: views.py class CartDestroyAPIView(DestroyAPIView): # DeleteView permission_classes = [IsAuthenticated] # Or anything else you want authentication_classes = [SessionAuthentication] # Or anything else you want serializer_class = productserializers queryset = Cart.objects.all() index.html <script> $(document).ready(function() { $.ajax({ url: 'http://127.0.0.1:8000/showdata ', dataType: 'JSON', success: function(data){ for (var i = 0; i < data.length; i++) { var row = $('<tr><td style="font-style:bold">' +data[i].product.name+'</td><td style="font-style:bold">' +data[i].product.price+'</td><td><a href=' +data[i].product.link_href+'><button type="button" class="btn btn-outline-success">Buy</button></a></td><td><button onclick="destoryCart('+data[i].product.id+')" type="button" class="btn btn-outline-danger">DELETE</button></td></tr>'); $("#tableProduct").append(row); } } }); }); const destoryCart = (id) => { let url = `http://127.0.0.1:8000/showdata/${id};` $.ajax({ beforeSend: function(xhr){xhr.setRequestHeader('X-CSRFToken', "{{ csrf_token }}"); }, url: url, type: 'DELETE', success: (data) => { console.log("deleted!"); }, error: (err) => { console.log(err); } }); }; </script> urls.py path('cart_destroy/<int:pk>', views.CartDestroyAPIView.as_view(), name ='cart_destroy'), WHAT IS WRONG GOING WITH THIS CODE. -
How can I have an image field in a Django Model?
I wanted to have a feature on my website that allows you to click on a link near an image and have that take you to another page which displays the image and a description. I figured that I could do this with a Model that has an image field and a text field for the description, but I don't know how to store an image! Is there a function or such that allows you to have an image field in a Django model? If so, what is it and where do I need to store images relative to the models.py file for it to work? Thanks in advance.