Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
APITestCase. How to authenticate users outside of the test functions?
Background I used to authenticate users inside each test function Goal now I am trying to authenticate the user in the APITestCase class in order to use the same authentications in mutlable functions. Problem when I add the credentials in the class it seems not effecting the function? class TestTimeSheets(APITestCase): if (not User.objects.filter(username='newusername').exists()): user = User.objects.create( username='newusername', email='newusername@g.com', password='password', is_email_verified=True, is_role_verified=True, is_staff=True, is_superuser=True) else: user = User.objects.get(username='newusername') client = APIClient() lg_res = client.post('/users/login/', {'username': 'newusername', 'password': 'password'}, format='json') client.credentials( HTTP_AUTHORIZATION=f'Bearer {lg_res.data["access"]}') resp = client.get('/statistics/',) print('======================') print(resp.data) #🔴 this returns the correct data print('======================') def test_statstics(self): resp = self.client.get('/statistics/',) # self.assertEqual(create_res.status_code, status.HTTP_201_CREATED) print('======================') print(resp.data) #🔴 but this says you are not authenticated. print('======================') -
GeoDjango: How to create a circle anywhere on earth based on point and radius?
I have a similar question to this one. Using geodjango, I am wanting to draw a circle on a map with a certain radius in km. However, the suggested solution a) does not use km but instead degrees, and b) becomes an oval further north or south. Here is what I do: from django.contrib.gis import geos lat = 49.17 lng = -123.96 center = geos.Point(lng, lat) radius = 0.01 circle = center.buffer(radius) # And I then use folium to show a map on-screen: map = folium.Map( location=[lat,lng], zoom_start=14, scrollWheelZoom=False, tiles=STREET_TILES, attr="Mapbox", ) The result is this: How can I a) draw a circle that is always 3 km in radius, independent from the position on the globe, and b) ensure this is a circle and not an oval at all latitudes? -
django: setting up erlang and rabbitmq but some problem on window os for celery
I downloaded and installed erlnag (latest version:otp_win64_24.0) first and then intalled rabbitmq-server(3.8.16.exe). I tried to check if it works okay so I executed 'rabbitmq-server.bat' ( I did run this as administrator) but error, failed. another question, I would like to do some task, periodic task by celery on my project application. that's why I install this on my computer before deploying webserver. webserver system is ubuntu.... but I am doing this vertual environment anyway. so I think it should be no problem at all. am I right? I am just asking this just in case. -
How to download auto generated file in Django?
I am created a basic ocr system. When user uploads a PDF file to system I read it and created a xlsm file with the same name. I am using remote control with Azure (Windows). I created a download button. When I click it, downloads the file with same name, so it should work but appears a error. How can I fix this problem? <a href= "{% static path %}" class="btn btn-outline-primary btn-sm" download>Download Report File</a> in my views: name = pdf.pdf.name.replace(".xlsm", "").replace(".pdf", "") path = "C:/user/ocr/" + name + ".xlsm" Note: Uploaded and created files are stored outside of the project file. -
Django filter feature with ajax not working
I have a table for tracking job applications and im trying to implement a filter feature. I want to display the results with pagination. However, I am getting errors when trying to do so and can't seem to find my way out of it. I want the results to be displayed without the page being refreshed. Please help.... :((( Here is my code: template file <ul id="filter_list" class="dropdown-menu"> <li><a href="#">Alphabetical Order (A-Z)</a></li> <li><a href="#">Application Date (Ascending)</a></li> <li><a href="#">Application Date (Descending)</a></li> <li><a href="#">Closing Date</a></li> </ul> <div id="table_results"> <div> <script> $(".dropdown-menu a").click(function(){ var selected_filter = $(this).text(); $.ajax({ url:'{% url "stu_filter_applications" %}', data:{ "filter_category": selected_filter, }, dataType:'json', success: function (response) { //I want the page to not refresh here }, error: function (response) { console.log(response.errors); }, }); }); </script> views.py: def stu_filter_applications(request): if request.is_ajax(): filter_cat = request.GET.get("filter_category", None) student = StudentUser.objects.get(user=request.user) int_apps = InternshipApplication.objects.filter(student=student) int_app = [] applications = [] for app in int_apps: #for each application, grab the internship and the recruiter if filter_cat == "Alphabetical Order (A-Z)": internship = Internship.objects.get(id=app.internship.id) int_applications = InternshipApplication.objects.filter(student=student). order_by('internship.internship_title') if filter_cat == "Application Date (Ascending)": internship = Internship.objects.get(id=app.internship.id) int_applications = InternshipApplication.objects.filter(student=student). order_by('application_date') if filter_cat == "Application Date (Descending)": internship = Internship.objects.get(id=app.internship.id) int_applications = InternshipApplication.objects.filter(student=student). order_by('-application_date') if … -
Add ManytoMany in Django models
I am trying to add a m2m relationship with already created model objects like the following: class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) client_name = models.CharField(max_length=500, default=0) client_shipping_address = models.CharField(max_length=500, default=0,blank=True, null=True) class Group(models.Model): emp = models.ForeignKey(Employee, on_delete=models.CASCADE) name = models.CharField(max_length=500, default=0) groupmodels = models.ManyToManyField(GroupModels) sender_clients = models.ManyToManyField(Client) #### this one receiver_clients = models.ManyToManyField(ReceiverClient) warehouses = models.ManyToManyField(Warehouse) Here a group model can have multiple sender_clients. In my serializers I have added the Client serializer as well like the following: class GroupSenderClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = "__all__" read_only_fields = ('user',) class GroupsSerializer(serializers.ModelSerializer): groupmodels = GroupModelsSerializer(many=True) sender_clients = GroupSenderClientSerializer(many=True) ####this one receiver_clients = ReceiverClientSerializer(many=True) warehouses = WarehouseSerializer(many=True) class Meta: model = Group fields = "__all__" def create(self, validated_data): print("v data", validated_data) items_objects = validated_data.pop('groupmodels', None) sc_objects = validated_data.pop('sender_clients', None) rc_objects = validated_data.pop('receiver_clients', None) ware_objects = validated_data.pop('warehouses', None) prdcts = [] sc = [] rc = [] ware = [] for item in items_objects: i = GroupModels.objects.create(**item) prdcts.append(i) instance = Group.objects.create(**validated_data) print("sc objects", sc_objects) if len(sc_objects)>0: for i in sc_objects: print("id", i['id']) inst = Client.objects.get(pk=i['id']) sc.append(inst) if len(rc_objects)>0: for i in rc_objects: inst = ReceiverClient.objects.get(pk=i['id']) rc.append(inst) if len(ware_objects)>0: for i in ware_objects: inst = Warehouse.objects.get(pk=i['id']) ware.append(inst) instance.groupmodels.set(prdcts) instance.sender_clients.set(sc) instance.receiver_clients.set(rc) instance.warehouses.set(ware) … -
Having trouble getting a double header using HTML
I'm having trouble getting a double header set up. Both headers seem to be one on top of the other, especially when I inspect the header. This is on Django if that changes anything <body> <section><header class="site-header"> ... </header></section> <section><header class="site-header"> ... </header></section> </body> -
Search through hashids if it contains specific value Django-hashids
I am using django-hashids for my IDs and I have to have a search function that looks up the encoded IDs. Right now, this is how it works search_string = request.query_params.get(self.search_param, "") result = view.hashids.decode(search_string) But this one requires the whole hashid to return a specific value. If the hashid is for example qwerty123 I have to input the whole string so that I'll get the right item. Is there any way that even if I just input qwerty, it will return the IDs that contain the inputted string? -
Upload image using its URL and show it on frontend of website in Django
I am new to Django and I am working on a website that required me to upload lots of images because of which the overall size of my website increased to 500+ MB. I had already used Django Imagefield and store the uploaded image in my static folder from the admin panel, instead of that, I want to upload the image using URL from the admin panel and want to show that image into the frontend of my website. How can it be possible? Any help will be really appreciable. This is a code of my models.py class Place(models.Model): place_title = models.CharField(max_length=255) country = models.CharField(max_length=100,default=' ') location = models.CharField(max_length=100,default=' ') description = RichTextField() place_photo = models.ImageField(upload_to='photos/%Y/%m/%d/') place_photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/') place_photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/') place_photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/') place_photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/') is_recommended = models.BooleanField(default=False) one_strong_point_for_recommendations = models.CharField(max_length=100,default='In 2-3 words',blank='True') architecture = models.CharField(max_length=100) feature1 = models.CharField(max_length=100,default=' ') feature2 = models.CharField(max_length=100,default=' ') feature3 = models.CharField(max_length=100,default=' ') feature4 = models.CharField(max_length=100,default=' ') Explain_each_feature = RichTextField(default=' ') Reasons_to_visit = RichTextField(default=' ') story1 = RichTextField(default=' ') story2 = RichTextField(default=' ') story3 = RichTextField(default=' ') story4 = RichTextField(default=' ') Max_temperature = models.CharField(max_length=100,default='') Min_temperature = models.CharField(max_length=100,default='') sea_level = models.CharField(max_length=10000,default='') no_of_visitors = models.CharField(max_length=1000000,default='Around x million') closeness_of_the_destination = RichTextField() added_date = models.DateTimeField(default=datetime.now,blank=True) place_views … -
Modify field data from a different app on Django
In my website I'm working on I have custom user models in an app called users code: Views.py: from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): is_premium = models.BooleanField(default=False) points = models.IntegerField(default=0) classrooms = models.JSONField(default=dict) posts = models.JSONField(default=dict) admin.py: from django.contrib import admin from .models import CustomUser admin.site.register(CustomUser) This all works but I have a different app called files I need to modify the posts field in the CustomUser model from the views.py file in the files app. I think the answer to this has to do with foreign keys but for some reason I cannot wrap my head round them. -
What's the correct way to get websocket message do display in django template using django channels?
I'm trying to display stock market data from a third party api in realtime using channels and celery. I'm using celery to get data from the api and channels to receive and send the data to the client. My issue is that the data isn't rendering in the template and my python and javascript aren't showing any errors so I have no idea what's wrong. Help would be appreciated. ignore commented out code in snippets. tasks.py import requests from celery import shared_task from channels.layers import get_channel_layer from asgiref.sync import async_to_sync channel_layer = get_channel_layer() @shared_task def get_stock_info (): # request.session['sym'] = sym payload = {'symbol': 'nvda'} # r = requests.get('https://api.twelvedata.com/time_series?&interval=1min&apikey=177206d91bf247f2a09d14ee8f4a4f16', # params=payload) r = requests.get('https://api.twelvedata.com/price?apikey=177206d91bf247f2a09d14ee8f4a4f16', params=payload) res = r.json() price = res['price'] async_to_sync(channel_layer.group_send)('stocks', {'type': 'send_info', 'text': price}) consumers.py from channels.generic.websocket import AsyncWebsocketConsumer class StockConsumer(AsyncWebsocketConsumer): async def connect(self): await self.channel_layer.group_add('stocks', self.channel_name) await self.accept() async def disconnect(self): await self.channel_layer.group_discard('stocks', self.channel_name) async def send_info(self, event): msg = event['text'] await self.send(msg) index.html <!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.0"> <title>Document</title> </head> <body> <p id="#price">{{ text }}</p> <p id="description">{{ res.Description }}</p> <script> var socket = new WebSocket('ws://localhost:8000/ws/stock_info/'); socket.onmessage = function(event){ var price = event.data; document.querySelector('#price').innerText = price; } </script> … -
django.core.exceptions.ImproperlyConfigured the issue is caused by circular import
I am doing simple API project in the starting I did not got the error but now circular import error what is the actual error in my coding does it need anything to add in the settings.py or in urls.py and what are the major causes of the error -
In python Django I want to execute two statements on if else that if email is taken show message if employee id is taken show message
I have a html registration form where I am displaying if any username or email exists or not so if it exists then display username is taken and if email exists it will display email is taken but the problem is even if I give email in the email field in the html form it says username is taken but not email I tried elif statement it didn't worked the username is taken is working perfectly but not email. If anyone knows please help This is my views.py def Register(request): try: if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') try: if User.objects.filter(username = username).first(): messages.success(request, 'Username is taken.') return redirect('/register/') if User.objects.filter(email = email).first(): messages.success(request, 'Email is taken.') return redirect('/register/') user_obj = User(username = username , email = email) user_obj.set_password(password) user_obj.save() profile_obj = Profile.objects.create(user = user_obj ) profile_obj.save() return redirect('/login/') except Exception as e: print(e) except Exception as e: print(e) return render(request , 'register.html') -
How to match the question id in the nested table to the main table
const questionsData = useSelector((state) => state.questionsData) useEffect(() => { dispatch(getQuestionsData()) }, []) const columns = [ { title: 'Question No', dataIndex: 'key', key: 'question_no', }, { title: 'Scenario', dataIndex: 'description', key: 'description', width: '25%', }, { title: 'Total Marks', dataIndex: 'qn_total_mark', key: 'qn_total_mark', }, ] const expandedRowRender = () => { const columns = [ { title: 'Part Description', dataIndex: 'part_desc', key: 'key', }, ] return ( <Table columns={columns} dataSource={questionsData} /> ) } return ( <> <Table columns={columns} dataSource={questionsData} expandable={{ expandedRowRender }} /> </> ) } for question in questions: if question.question_id not in res: res[question.question_id] = { "key": question.question_id, "question": question.question, "description": question.description, "qn_total_mark":question.qn_total_mark, "part_desc": question.part_desc, } what i am trying to do is create a nested table to store the part_desc , however my nested table right now gives back all the part desc regardless of the question number,is there a way to store the part description matching the question number respectively -
how to print in django after filtering data using django-filters user input
i have a module children with 4 fields a. child _id ( pk) b. first_name c. middle_name d. last_name i have used django-filter app now I want the user filter the data and by clicking the button and get print of the filter data i have searching on internet tried installing xhtmltopdf, weasypdf but of no use .I am new to it. is there any way I can print report based on filteration done by user -
How to update django settings in AppConfig ready funciton or other way?
now i have a code: class BlueappsAccountConfig(AppConfig): name = 'myapps' verbose_name = 'myapps' def ready(self): settings.configure(MYAPPS_CONFIG={"APP_CODE": "appcode"}) exist_middleware = settings.MIDDLEWARE add_my_middleware = ("myapps.middleware.MyMiddleware",) + exist_middleware settings.configure(MIDDLEWARE=add_my_middleware ) i have my middleware and some DIY configuration,i need to update django settings so that MyMiddleware to work and update some myapps config to settings,but i have error: Traceback (most recent call last): File "C:\python\py368\lib\threading.py", line 916, in _bootstrap_inner self.run() ... app_config.ready() File "F:\account_django_test\myapps\MyAppConfig.py", line 12, in ready settings.configure(MYAPPS_CONFIG={"APP_CODE": "appcode"}) File "F:\account_django_test\venv\lib\site-packages\django\conf\__init__.py", line 107, in configure raise RuntimeError('Settings already configured.') RuntimeError: Settings already configured. what should i do if i want to edit settings on before app installed or edit it on settings not configured moment? -
Javascript not reflected on Django Project
I am trying to show a carousel box/ banner in my page but I am having an issue with the JavaScript it is not appearing. I have borrowed the HTML/ CSS and JS from https://codepen.io/StephenScaff/pen/egOedp/ and I am trying to apply the same concept to my Django Project. I have added the HTML in a file called projects.html and in the base file I have linked a new CSS file simple.css with css format which in my Django project project working but my issue is when I tried to implement to JS file here is what happened in my trials. Also the next and previous buttons are not showing Trial 1 I have added under the HTML file projects.html but the js code appeared under the banner image like normal text {% block script %} Added the JS code... {% endblock script %} Trial 2 in my base.html file I created a new file called simple.js and added in the static folder and linked it but still it didn't reflect on the server. <script src="{% static 'simple.js' %}"></script> My question What am I doing wrong causing this confusion and how to implement the JS code for this simple banner to … -
module 'django.http.request' has no attribute 'user'
I want to save author automatically in article model,i searched a bit and came across these references: Here and Here Each of them and other references on the Internet said that to save the user field, the save_mode method should be used in the admin.py file. Then I wrote this code for it in admin.py: class ArticleAdmin(admin.ModelAdmin): list_display = ('author','simple_created','slug','title_en','views','status') search_fields = ('desc_en','desc_fa','title_en','title_fa','body_en','body_fa') ordering = ['-created'] def save_model(self, request, obj, form, change): obj.author = request.user obj.save() return super().save_model(request, obj, form, change) But the problem is that I don't have access to the User through request and I get the following error: AttributeError at /admin/blog/article/10/change/module 'django.http.request' has no attribute 'user' I think Django uses django.http.request by mistake but I did not import it at all Django version : 3.2 Python version : 3.8.5 How can I solve this problem and access the user? -
I have installed requests but I still get ModuleNotFoundError: No module named 'requests' (Django)
If I do pip3 install requests I get (Requirement already satisfied), If I do pip install request I get (Requirement already satisfied), python3.9 -mpip install requests (Requirement already satisfied), It seems like I have requests already installed but still I get "ModuleNotFoundError: No module named 'requests'" I'm having a file with this code in my django project import requests def client(): credentials = {"username": "admin", "password": "hampus123"} response = requests.post("http://127.0.0.1:8000/api/rest-auth/login/", data=credentials) print("Status Code:" , response.status_code) response_data = response.json() print(response_data) if __name__ == "__main__": client() -
How does Django change Boolean values dynamically?
Hi how do I approach telling django : --> Upon user submitting a Post, and click is True --> Turn other Post False (there can only be one post that is true) -
How to set value to django-select2 field Programmatically (on button click) using javascipt?
In my django app I have a WorkerModel and a ProvinceModel, each worker has a province_id field. I have define a form for Worker using ModelSelect2Widget (django_select2) for province_id. I want to know how to set a value to province_id field using javascript. The idea is that when a button is clicked we make an ajax request getting the id and name of the province and I want to set the value of province_id to the province id I just got from django_select2.forms import ModelSelect2Widget class WorkerForm(forms.ModelForm): class Meta: model = WorkerModel exclude = ("id",) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'province_id' : ModelSelect2Widget(model=ProvinceModel, queryset=ProvinceModel.objects.filter(), search_fields=['des_prov__icontains'], attrs={'style': 'width: 100%;'}), } in the template <script> //on a button click a want to set the value of province_id $(document).ready(function () { $('#id_province_id').djangoSelect2({ placeholder: 'Seleccione una opción', escapeMarkup: function (markup) { return markup; }, language: { noResults: function () { return "No se encuentran resultados."; } } }); }); </script> -
Progress <input type=“file”> to other form when submit is pressed
This all works fine but what i want to do is have the name of the file i was uploading stored in a hidden input type so when i submit my form with text fields,the name of the image can be submitted to the database. I have noticed that when i submit my main form to database, the image has been saved into the database. I am able to save it in a temporary folder named "media". However, whenever I edit the form, the image cannot be retrieve anymore My question is how do i pass data of the uploaded file to my other form? This is my newclaim.html (Form which submit the receipt) <form action="/newclaim/" method="post" enctype="multipart/form-data"> <div> <input id="receipt" type="file" name="receipt_field"> </div> </form> This is my existingclaims.html (Form which retrieve the receipt) <form method="POST" action="/editclaims/{{claims.id}}" enctype="multipart/form-data"> <div> <input id="receipt" type="file" value="receipt" hidden> <label for="receipt"> {{ claims.receipt }} </label> </div> </form> This is my views.py # Submit a new Claim def newclaim(request): context = initialize_context(request) user = context['user'] if request.method == 'POST': receipt = request.FILES['receipt_field'] ins.save() return render(request, 'Login/newclaim.html/', {'user':user}) # Edit a claim def editclaims(request,id): context = initialize_context(request) user = context['user'] # get original object claims = SaveClaimForm.objects.get(id=id) … -
Dynamically add HTML items to the right of previous item instead of below
I'm sure this is an amateur question, but I am having difficulty figuring out how to dynamically add html items to the right(same horizontal level) inside of my div. When I add a new Label it adds below the previous label I added. How do I place the new Label to the right of the previous label I added to my webpage? My javascript: <script> $(document).ready(function(){ $("#comp").click(function (e){ event.preventDefault() $('#items').append('<label>My Label</label>); }); }); </script> My html: <div id = "items"> </div> <input type="button", name = "comp" value = "Compare" id="comp"></input> -
Python: unsupported format character ''' (0x27) at index 350
I've got this error using the MySQL db backend for django. The query I'm trying to execute (it worked perfectly with MariaDB connector): cursor.execute("SELECT a.*, COALESCE( NULLIF(a.aa_change_ref_gene, '.'), NULLIF(a.gene_detail_ref_gene,'.') ) AS variant, b.*, c.* FROM `db-dummy`.specimen_genome_data c JOIN `db-dummy`.genome_info a ON a.record_id = c.genome_id JOIN `db-dummy`.specimen_data b ON b.record_id = c.specimen_id WHERE a.gene_name LIKE concat(?, '%') ORDER BY a.gene_name LIMIT 30", (gene,)) What I've tried: Basically replacing the '%' for "%" and '%%' Then I am getting this error for the "%" case: Exception Type: TypeError Exception Value: not all arguments converted during string formatting And this error for the '%%' case: Exception Type: ProgrammingError Exception Value: not all arguments converted during bytes formatting Exception Location: /home/prime/.env/intervar/lib/python3.6/site-packages/MySQLdb/cursors.py in execute, line 203 -
SQLAlchemy optional ForeignKey
In SQLAlchemy.orm I have the following class: class Table(Base): __tablename__ = 'table' id = Column(Integer, primary_key=True) src = Column(Integer, ForeignKey('other.id')) dst = Column(Integer, ForeignKey('other.id')) source = relationship("Other", foreign_keys=[src]) destination = relationship("Other", foreign_keys=[dst]) I want to make the src and source optional which means those records could be empty in the table. In Django's ORM, I used to make a model field optional by using blank=True and null=True like: src = models.ForeignKey(Other, blank=True, null=True) There is a default parameter for each column in SQLAlchemy as well. I tried: src = Column(Integer, ForeignKey('other.id'), default=None) But it doesn't work.