Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the info of a element (Django)
I am making a fake social media site as a school project and currently, I am adding the friending feature. What I do is I have a list of people who have sent the receiver a friend request and print those using a loop. What I need to do right now is create a button that allows people to accept that particular person as their friend and I don't know how I might get to know the accept button against which person was clicked. Here is what I have tried: HTML: </tr> {% for element in rel_receiver_lst %} <tr> <td> {{element}} <form action = "{%url 'acceptFriend' %}" method = "POST"> {% csrf_token %} <input type = "hidden" name = "profile_pk" value = {{element.pk}}> <button type = "submit" class = "waves-effect waves-light btn">Add to Friends</button> </form> </td> </tr> Views: def acceptFriend(request): if request.method == "POST": print("accepting friend request") pk = request.POST.get("profile_pk") user = request.user sender = User_Info.objects.get(pk = pk) print(pk) receiver = User_Info.objects.get(user = user) rel = Relationship.objects.create( sender = sender, receiver = receiver, status = "accepted" ) rel_to_delete = Relationship.objects.filter(sender = sender).filter(receiver = receiver).filter(status = "sent") rel_to_delete.delete() return redirect("social") Where am I going wrong and what as some good resources … -
Migration for Django library
Please tell me how to migrate the library for Django. There is a library written for the old version of Django. In newer versions of Django, the on_delete parameter is required. I've tweaked the lib for newer versions of Django. But since a parameter has been added to the model, it is necessary to migrate. -
Python script with Arguments in Django views
I have a python script that runs like this: python age_detect.py --image images/name.jpg --face face_detector --age age_detector Also i have a Django application which is Uploading form, where you can upload your photo and all i need is to after uploading an image, i could run the script with that uploaded image and show it back in application. My views.py: from django.shortcuts import render from .forms import ImageForm def image_upload_view(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() img_obj = form.instance return render(request, 'upload.html', {'form': form, 'img_obj': img_obj}) else: form = ImageForm() return render(request, 'upload.html', {'form': form}) Could you guys help me with my question? -
Which stack is best to build custom local media server? [closed]
I was looking to build a custom local media server that will serve some videos and images from a local folder. This local folder will have certain structure in which videos and images will be stored. I wanted to know which tech-stack (like flask-django or django-rest + react ...) to use (so that it'll be easier to develop). I'm kinda confused with how to start this project. Requirements: stream local video files display local images parent directory which contains the videos and images can change location, so the project should take full path of parent directory and then serve the contents Any help in this regard will be highly appreciated !! -
How to keep a Django application private?
I am building a Django-based financial project which is made up of 3 applications and I would like to keep the code of one of them private. This means that third parties who will be working with me on this project for code review and features development would only be able to read and update the code of 2 applications and I would be the only person to control the code of the private application. Currently the 3 applications are hosted on a single AWS instance but I could host 2 applications on one AWS instance, and the private application on another AWS instance which I would be the only one to have access to. The applications could then communicate together with GraphQL but the problem is that they are currently linked by the models. What is the best way to do this ? Do I need to rewrite the code to unlink the models of applications 1 and 2 with application 3 ? Or is there an easiest way to do this ? -
Trable create app django in docker-compose
Need create app in django project in docker conteiner. How do? I try docker-compose exec -it container_name django-admin startapp my_app_1 -
OpenAPI Swagger change schemes in Django(drf-yasg)
I am using DRF-YASG to create a swagger everything works fine but I am unable to create schemes. For example in my local I can see the url starting from http and in swagger ui I can see a dropdown. By default is only suggests one schemes that is HTTP and I want both the schemes like http and https. enter link description here in this accepted answer I can achieve that by using: schema_view = get_schema_view( openapi.Info( ... ), url='https://example.net/api/v1/', # Important bit public=True, permission_classes=(permissions.AllowAny,) ) But I want bot the schemes in my server I want to use https and local I want to use http. I have read all the docs there but I ma unable to find any particular solution. -
Create object on startup and share across requests
I would like to use my Django application as a relay for a session-based online service and share this session among all users. For this, I've configured a python-requests Session object. I would like to initialise this Session when Django starts up and keep it alive forever. My idea is to have all requests to my Django application share the session object by allowing the view for the particular request access the session object. In Flask setting this up (for experimental purposes) is fairly easy: from flask import Flask, render_template, request, session from requests import Session app = Flask(__name__) session = Session() session.post() # Setup Session by logging in @app.route("/") def use_session(): reply = session.get() # Get resource from web service return jsonify(reply) Here session would be created when starting and can be accessed by use_session(). I struggle to set up the same in Django though. Where would be the preferred place to create the session? -
Django, FastAPI and DRF
I want to make a project, which uses Django as backend, PostgreSQL as database and FastAPI with Django REST Framework for REST. Don't see any problems with making a project just with Django, DRF and Postgres, but face with difficulties when speak about FastAPI and DRF at the same time. So there is no problem in connecting Postgres to Django, and there is no problem to make endpoints for DRF. But how can I connect fastapi? Where to place endpoints and how to run all this stuff together? In some examples I saw that FastAPI isntance is initiated in WSGI.py and then server runs from calling commands such like this: uvicorn goatfish.wsgi:app But i am not sure that it works like this when I mix more than only Django and FastAPI. Are there any advices about making project with such a structure? Or maybe someone have a repository with such kind of project on github? -
How to save request.FILES.get('img') to base64encode formate in django models and decode the base64 see the image
How to save request.FILES.get('img') to base64encode formate in Django models without uploading into folder like upload ext please any on help me out regarding this? -
Can I disable Django DEBUG mode for specific functions so as to avoid generating the detailed error page?
One particular function in my Django server performs a lot of computation during a request and that computation involves a lot of local variables. When an error is thrown during the computation, Django spits out all the function's local variables onto the error page. This process takes Django 10-15 seconds (presumably because of the number/size of my local variables)... I want to disable the error page for just that particular function, so I can get to see the simple stacktrace faster. I tried using the sensitive_variables decorator but that doesn't do anything when DEBUG=True. I also tried simply catching the exception and throwing a new exception: try: return mymodule.performComputations(self) except Exception as e: raise Exception(repr(e)) but Django still manages to output all the local variables from the performComputations method. My only option right now is to set DEBUG=False globally anytime I'm actively developing that particular code flow / likely to encounter errors. Any other suggestions? Thanks! -
How to drop a task from the Celery queue if connection is lost?
I'm using Celery beat and workers to retrieve the latest news every 30 mins. At night when my computer is asleep the internet connection is lost. Then in the morning the same task wants to run several times to catch up for the lost attempts. How can this tasks not pile up in case the connection is lost? In the Admin section of Django there's an option called "Expires timedelta with seconds" but it doesn't seem to be doing what I need. Any suggestions? -
How do I save images directly into a MySQL database as a BLOB using django? These images are uploaded dynamically through the django admin panel?
What i want is that when i upload an image from the django admin panel, the image should be saved as a blob in MySQL database and not save the URL as django does when we use the imageField model. What is happening: upload image through admin panel -> url stored in database, image in folder -> image fetched via url in template What I want: upload image through admin panel -> convert image to blob -> store blob in database -> image fetched directly from database -
Install python 3.9 in linux server which is already having 2.7 without any side effect
My companies production linux server has python 2.7. Also, none of my colleagues know if anything is using python 2.7 on that machine. I want to use latest django on it so I want to install python 3.9 on that server. If I do "yum install python" will it cause any negative impact on my machine? -
data preprocessing in Django
I am currently working on a project where I want to take sound data as input and convert it to an image file(logarithmic scale). I already have a code for this (data preprocessing) and now I want to use it in django(views.py). Is it possible to do so?? This is my code for preprocessing, def preprocessing(af): image_storage=[] # read file (Extract sample rate and amplitude array over time) for x in af: sample_rate, sound_data = wavfile.read(x) # collect some additional info about the data data_points = sound_data[:, 0].size length = data_points / sample_rate data_shape = sound_data.shape data_type = sound_data[:, 0].dtype # fourrier transform y_fourrier = np.abs(fft(sound_data[:, 0])) x_fourrier = np.linspace(0.0, sample_rate, data_points, endpoint=True) y_fourrier = y_fourrier[0:data_points // 2 + 1] x_fourrier = x_fourrier[0:data_points // 2 + 1] #transform to log scale y_fourrier_db = np.log10(y_fourrier) #plot fourrier data (apmlitude logrithmically) r=plt.plot(x_fourrier, y_fourrier_db) r.axis("off") r.margins(0, 0) image_storage.append(r) return image_storage -
How to assign a customer to a user in .Django?
I created a system and in this system, there are several users and customers. What I want to create an assign function. A customer should assign to a user. For example, I have a customer list. When the user clicks a button, the user will see a list that other users and select one of them. After that, the customer's name will be listed in the different assigned customers list of the selected user. How Can I do that? models.py class Customer(models.Model): customer_name = models.CharField(max_length=20) country = models.CharField(max_length=20) address = models.CharField(max_length=100) VATnumber = models.CharField(max_length=10) telephone = models.CharField(max_length=10) email = models.CharField(max_length=30) contact_person = models.CharField(max_length=30) company = models.CharField(max_length=20) id = models.AutoField(primary_key=True) class UserProfile(AbstractUser, UserMixin): company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False) user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) views.py def customer_list(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company.comp_name) myFilter = TableFilter(request.GET, queryset=customer_list.all()) context = { 'customer_list': customer_list, 'myFilter': myFilter, } return render(request, 'customer_list.html', context) customer_list.html <table id="multi-filter-select" class="display table table-striped table-hover grid_" > <thead> <tr> <th>Customer Name</th> <th>Country</th> <th>E-Mail</th> <th>Phone</th> <th>VAT Number</th> <th>Operations</th> </tr> </thead> <tbody> {% for customer in customer_list %} <tr> <td>{{customer.customer_name}}</td> <td>{{customer.country}}</td> <td>{{customer.email}}</td> <td>{{customer.telephone}}</td> <td>{{customer.VATnumber}}</td> <td> <div class="row"> <a href="/customers/{{ customer.id }}/profile" class="btn … -
Django migrations -- how do I wipe a model as part of a migration?
I have a workflow where a model is generated by a script from some data also stored in the database: SourceData -> management command generates -> Results When I change how that Results model is generated, like adding a new field, I don't want to set a default value or update the existing models, I want to delete all of them and just run the script again to regenerate them with the new field: Delete all Results -> run management command v2 -> Results (+ new field) Is there an easy way to do this? All I've found online is how to accomplish this by deleting the whole database, which isn't what I want, I just want to drop this one table and recreate it. -
I am not migrate in python django
Operations to perform: Apply all migrations: admin, auth, contenttypes, main, sessions Running migrations: Applying main.0004_auto_20210301_2201...Traceback (most recent call last): File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 411, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such function: JSON_VALID The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\migrations\operations\fields.py", line 236, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\schema.py", line 138, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\base\schema.py", line 571, in alter_field self._alter_field(model, old_field, new_field, old_type, new_type, File "C:\Users\devia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\schema.py", line … -
How can we do athentication and autherisathion with Django + Rest + MongoDb
How can we do Django + Mongodb + rest authentication and autherisation ? -
How to access getlist items in django?
This is my template : {% for pr in productlist %} <ul name="myList"> <li>{{ pr.productname }} <input type="hidden" name="mylist" id="prname" value="{{ pr.productname }}"></li> <li><input type="number" name="mylist" id="prnumber"/></li> </ul> {endfor} in this list i have items or more. i using getlist() method and can print items in view. here is my view : data = request.POST.getlist("mylist") for item in (data)): print (item) result is : product1 1 product2 6 product3 4 my problem is here, it returned all items, i want just return : name = item.prname number = item.prnumber one by one not all. how i can achieve it? -
502 Bad Gateway Error in Django, nginx, DigitalOcean, Gunicorn but only sometimes
I am working on a Django app deployed on DigitalOcean with Gunicorn, Nginx, Postgres. Everything working fine but I am facing a strange problem of 502 Bad Gateway only sometimes when I generate PDF using xhtml2pdf. However, the problem isn't constant, it shows only sometimes. My Nginx and Gunicorn timeout is set to 30s but the error comes within 30s. This is my code where I am generating PDFs, def link_callback(uri, rel): # use short variable names sUrl = settings.STATIC_URL # Typically /static/ sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/ mUrl = settings.MEDIA_URL # Typically /static/media/ mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/ # convert URIs to absolute system paths if uri.startswith(mUrl): path = os.path.join(mRoot, uri.replace(mUrl, "")) elif uri.startswith(sUrl): path = os.path.join(sRoot, uri.replace(sUrl, "")) # make sure that file exists if not os.path.isfile(path): raise Exception('media URI must start with %s or %s' % (sUrl, mUrl)) return path def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result, link_callback=link_callback) if not pdf.err: if for_mail: return result.getvalue() else: return HttpResponse(result.getvalue(), content_type='application/pdf') return None I am also showing logos on generated PDFs, hence the link_callback function. I don't think the problem is from Nginx or gunicorn's config files, as … -
Ubuntu problems for Django translation
I've deployed a django app to an ec2 ubuntu 20.04 instance, during development (using windows) the translation worked fine but now that I'm deploying the site to ubuntu the translation is not working. I've found out, according to other stackoverflow questions that ubuntu doen't like folders named in example 'es_mx' in locale directory, but it take in consideration 'es_MX' the problem here is that I just want to use 2 character language codes like 'es' but it's not working, Is there a way around this problem? Any help would be appreciated -
I want to create a Paid time off form in Python
I'm thinking I create a Paid time off form for internal use from a friend's company. My friend says that he wants me to make it with Python. Is it possible with Python (Flask or Django? Flask? Flask is better?)? If so, somebody can recomend some articles or youtube tutorials for reference? It'll help a lot. This is how it is. This is for an employee to submit PTO requests. Employee login. Employee picks the Supervisor's name. (drop-down manual) Employee picks the PTO form (the system will generate a "number", in sequence) Employee fill-up the form, (PTO date, time). Employee submit the form. The system notifies the Supervisor. Supervisor login. Supervisor approval (yes or no Supervisor log-out (return the form) The system notifies the employee and the HR desk. (if not approved, allow employee appeal and re-submit) HR approves the final HR closes the request, The request will be filed into the database. The HR inquiry history, and print a hard copy. -
Fetch the the restaurants in a radius
I want to get the list of all restaurants within a radius of my current location How can i do this. I have tried something ,,just have a look models.py class Restaurant(models.Model): restaurant_owner = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="restarant_details", null=True, blank=True) latitude = models.CharField('Latitude', max_length=30, blank=True, null=True) longitude = models.CharField('Longitude', max_length=30, blank=True, null=True) location = models.PointField(blank=True, null=True) owner_name = models.CharField(max_length=200,null=True,blank=True) restaurant_name = models.CharField(max_length=200,null=True,blank=True) registration_no = models.CharField(max_length=200,null=True) registration_date = models.DateField() registration_mobile = models.CharField(max_length=200,null=True) views.py class RestView(viewsets.ViewSet): permission_classes = [IsAuthenticated,OnlyUser] def list(self, request): try: radius = 2 print(self.request) user_location=request.user.location print(user_location) if not user_location: return Response({"message": "User is not Available","success":False},status=status.HTTP_400_BAD_REQUEST) #query_set=Restaurant.objects.annotate(distance=Distance('restaurant_owner__location',user_location)).order_by('-distance') #query_set=Restaurant.objects.filter(location__distance_lt=(user_location, Distance(km=radius))) #query_set=Restaurant.objects.filter(restaurant_owner__location__dwithin=(user_location, Distance(mi=90))) #query_set=Restaurant.objects.filter(location__distance_lt=(user_location,Distance(m=5000))) query_set=Restaurant.gis.filter(location__dwithin=(user_location, 0.008)) serializer=RestaurantSerializer(data=query_set,many=True,context={'request': self.request}) serializer.is_valid() serializer.save() return Response({"message": serializer.data,"success":True},status=status.HTTP_200_OK) except Exception as e: traceback.print_exc() return Response({"message": str(e),"success":False,},status=status.HTTP_200_OK) I have tried many things from internet did not anything suitable some please guide me -
Form values are not overwritten when changed - they are stuck at their default values
I have the following view: @login_required def my_view(request): instance = my_model(user=request.user) form = my_model_form(request.POST,instance = instance) if request.method == "POST": if form.is_valid(): form.save(commit=False) #Field1 and field2 is already in the form (its the input) # Do some back-end operations to get values for the remaining fields df = some_util_function() form.field3 = df["field3"] form.field4 = df["field4"] form.field5= df["field5"] form.save() return redirect("my_html") else: form = my_model_form() context = { "form":form } return render(request, "discounttracker/my_html.html",context=context) and the problem is that field3,field4,field5 are not changed. I have even tried to hard-code them to 1000, 2000,3000 (they are FloatField(default=0)) but they remain at their default value when written to the DB. What am I doing wrong here?