Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django communicating with another python application?
Is it possible to have django running on the server and one application from django inter communicating with another python process say that I developed and fetching a response from it or even make it just do a particular action? It can be synchronous or asynchronous; I have some idea of being asynchronous where some package like hendrix, crossbar.io or even celery can be used. But I don't understand what would be the name for this inter-communication and how should I plan the architecture for this. Going around my head I have the two following situations I'm seeking a plan to be developed: 1. Say I have django and an e-mail sender with the python package smtp. A user making a request to a view would make django execute my python module I developed for sending an email to a particular user (with a smpt server from google/gmail). It could be synchronous or asynchronous. OR 2 I have django (some application) and I want it to communicate with some server I maintain; say for making this server execute some code or just fetch a file (if it is an ftp server). Is this an appropriate situation to point to the … -
Pushed Django project to GitHub with Pycharm - now not working
Sorry for the generic question; I'm not sure how to best classify the problem. I had a Django project that I was working on locally, then I pushed up to GitHub to collaborate with someone (I'm completely new to GitHub). I did this using pycharm and the project was copied into a subdirectory of PycharmProjects. It seemed to work fine. I didn't work on it for a week or so, during which time I upgrated to Catalina. I've come back to work on the project and it's completely broken! I can't get the development server up and running from either the PycharmProjects directory or my original working directory on the desktop. I suspect in the PycharmProjects folder it's a path or dependency problem, but I didn't change anything in my original folder. I can activate the virtual environment, then I get these errors: (ll_env) Davids-MacBook-Pro-2:POM_Journal_Club davidhallsworth$ python manage.py runserver File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax (ll_env) Davids-MacBook-Pro-2:POM_Journal_Club davidhallsworth$ python3 manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent … -
drf saving objects in database
I am overriding post() method of generic views in DRF but. When I send request it saves two objects in django admin instead of one. class CartApiView(generics.ListCreateAPIView): queryset = Cart.objects.all() serializer_class = CartSerializer # def perform_create(self, serializer): # serializer.save(user=self.request.user) def post(self, request, pk=None, *args, **kwargs): try: user = self.request.user product = Product.objects.get(pk=request.data['product']) quantity = int(request.data['quantity']) except Exception as e: print(e) return Response(status=400) existing_cart_product = Cart.objects.filter(user=user, product=product).first() if existing_cart_product: existing_cart_product.quantity += quantity existing_cart_product.save() else: new_cart_product = Cart.objects.create(user=user, product=product, quantity=quantity) new_cart_product.save() serializer = CartSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(user=self.request.user) return Response(serializer.data) if I send post request it saves two objects in admin panel. For example { "product": 1, "quantity": 1 } here two objects are saved with one post request. If again I am going to post same product and same quantity. The objects number will be 3 but last one that is checked in here quantity is 2. More clearly, When I post same product and same quantity it is incremented by one and last checked one's quantity is also incremented by one. The problem is I do not need that one. I need to save only one object when I post and If I add same product the quantity should be incremented by … -
django-rest-swagger UI doesn't have form for POST request body (function based view)
I have this function-based view with django-rest-swagger decorated. However, I can't find place in UI that allow me to post the payload (request.body). I saw a couple solutions about doing it with class-based view, but I was wondering if there is a way to do it with function-based view. Thank you in advance! @renderer_classes([JSONRender]) @api_view(['POST']) def some_method(request): body = json.loads(request.body) return JsonResponse({'status': 'ok'}) -
I am trying to create a graphql mutation , where i cannot add the categoryNode as a input feild to AddEquipment mutation
category model this my category model class Category(models.Model): _id = models.ObjectIdField(primary_key=True) name = models.CharField(max_length=100) Category node I've created a category node using relay class CategoryNode(DjangoObjectType): class Meta: model = Category filter_fields = ['name', 'equipments'] interfaces = (relay.Node,) add equipmemt mutation while mutation i need to add a category object to equipment object in mutation inputs class AddEquipment(relay.ClientIDMutation): class Input: name = graphene.String(required=True) category = graphene.Field(CategoryNode) equipment = graphene.Field(EquipmentNode) @classmethod def mutate_and_get_payload(cls, root, info, **inputs): equipment_instance = Equipment( name=inputs.get('name'), category=inputs.get('category') ) equipment_instance.save() return AddEquipment(equipment=equipment_instance) by this code iam getting error like this class AddEquipment(relay.ClientIDMutation): class Input: name = graphene.String(required=True) category = graphene.Field(CategoryNode) equipment = graphene.Field(EquipmentNode) @classmethod def mutate_and_get_payload(cls, root, info, **inputs): equipment_instance = Equipment( name=inputs.get('name'), category=inputs.get('category') ) equipment_instance.save() return AddEquipment(equipment=equipment_instance) -
How can I run my python selenium scripts using browser?
I've written python selenium script on Django framework. Now I have no clue how can i run the test case using browser. I can execute the test case through terminal. Now i need to execute the same test case through browser. Like with URL i need to start executing the test case -
Is there any way to get the step-by-step solution in SymPy by myself coding?
2x^3+x^2-x+y : Steps for Derivative: 1. The derivative of the constant y is zero. 2. Apply the power rule: x2 goes to 2x 3. The derivative of a constant times a function is the constant times the derivative of the function. - Apply the power rule: x goes to 1 - So, the result is: −1 4. The derivative of a constant times a function is the constant times the derivative of the function. - Apply the power rule: x3 goes to 3x^2 - So, the result is: 6x^2 The answer is: 6x^2 + 2x − 1 -
Django fixture 'python manage.py loaddata' in a UTF-8 format?
I currently have a fixture file in a json format and it's based on utf-8. So when I view the file in VSC, I can successfully read the Korean letters. However, when I try to fill in the Django DB (SQLite) with the python3 manage.py loaddata (fixturefilename) command, and try to view the DB contents with the following view method, def see_list(request): if request.method == 'GET': all_list = [item for item in Item.objects.all().values()] return JsonResponse(all_list, safe=False) I only see \ud544\uc694\u2461 these kinds of output and no Korean. Is there a way to loaddata based on utf-8? -
Add model field to non-model serializer in Django
I'm using Django 2.x I have a serializer for validating the request. (Not ModelSerializer) class ExecuteSerializer(serializers.Serializer): database = serializers.IntegerField(required=True) query = serializers.CharField(required=True) user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) def validate(self, attrs): user = attrs.get('user', None) try: database = Database.objects.get(pk=attrs.get('database', None), collection__user=user) except Database.DoesNotExist: raise ValidationError({ 'database': ['Does not exists'] }) attrs['database'] = database return attrs database is reference to the Database model. I want user to pass the database id in the database field but got is converted to database object after validation. I tried to override the validate() method and assign the database object to the database field but it gives error TypeError: int() argument must be a string, a bytes-like object or a number, not 'Database' -
Invoking a Google Cloud Function from a Django View
I have created a Google Cloud function that can be invoked through HTTP. The access to the function is limited to the Service account only. If I had a Django View which should invoke this function and expect a response? Here is what I have tried 1) Before starting Django I set the environment variable export GOOGLE_APPLICATION_CREDENTIALS 2) I tried invoking the function using a standalone code, but soon realised this was going nowhere, because I could not figure out the next step after this. from google.oauth2 import service_account from apiclient.http import call SCOPES = ['https://www.googleapis.com/auth/cloud-platform'] SERVICE_ACCOUNT_FILE = 'credentials/credentials.json' credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) Google's documentation does give you documentation around the API, but there is no sample code on how to invoke the methods or what to import within your Python code and what are the ways to invoke those methods. How do you send a POST request with JSON data to an Cloud Function, with authorization through a service account? -
Css changes is not reflecting in Django
I'm doing Django project, my issue is when I change colors in style.css file in static folder, the changes aren't reflecting on the website again the same old colors are coming. ScreenShot of my project file directory -
Django Token Authentication with Cookie
I am using Django REST framework with OAuth2Toolkit library to implements OAuth2 on my site, My frontend is built with React, and I am trying to connect both with storing the token inside a httponly-cookie. The problem im facing is that the library OAuth2Toolkit checks the HttpRequest for an Authorization header with Bearer key and value. Tho I am sending the token via cookie... (I don't want to save the token in localStorage, I heard it is really unsafe to do it this way) How do I connect my BE and FE for a safe authentication? -
Django - How to use filter with exclude well?
I can't figure out the way to build a query, so I need some help here! This is the models: class User(models.Model): id = models.BigAutoField(primary_key=True) name = models.TextField() class Employee(models.Model): user = models.ForeignKey(User, primary_key=True) class Service(models.Model): id = models.UUIDField(primary_key=True) user = models.ForeignKey(User) employee = models.ForeignKey(Employee) views = models.ManyToManyField(Employee) So, an employee need to get the first service that does not have an assigned employee, the query would be the following: Services.objects.filter(employee__isnull=True)[:1] An employee can see a service only once, after the employee see the service is added to views in Service model like service.views.add(employee). Because the query is made for employees, I need to exclude the services that the employee has already seen before, I tried something like that: Services.objects.filter(employee__isnull=True).exclude(views__views__employee_id=1)[:1] How should I do it? Thanks. -
How to run Gunicorn on HTTPS on CloudFoundry
I need to host my Django application using Gunicorn on Cloudfoundry on port 443, HTTPS. I am getting error: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. Which is resulting into Internal server error. How should I add add SSL. What are server.cert and server.key files? How to add them. -
Need help in creating a database schema
Current Database Schema - I have these 3 tables, Curriculum, Assignment, and Student. Every Student is assigned a Curriculum through a ForeginKey relationship between Student and Curriculum. Every Assignment possesses the same relation with the Curriculum using a ForeginKey. Problem Statement - There are around 100 Assignments for each Curriculum, the problem is, some students need to be exempt from some assignments, so I want a way that I can exempt a Student from Assignments 1, 2, and 3 but have the rest of the students do the assignment 1, 2 and 3. My solution that failed - What I tried was, creating a ManyToManyField in Student table in relation to Assignment table. However, having to add hundreds of assignments manually would be ridiculously time-consuming for each student. class Curriculum(models.Model): name = models.CharField(max_length=50, null=False) subject = models.CharField(max_length=30, choices=SUBJECT) grade_level = models.CharField(max_length=20, choices=CURRICULUMGRADE, null=False) tracking = models.CharField(max_length=20, choices=TRACKING, null=False) required = models.CharField(max_length=20, null=True) recorded_from = models.CharField(max_length=20, choices=RECORDED, null=False) semesterend = models.CharField(max_length=50, null=True) username = models.CharField(max_length=50, null=True) password = models.CharField(max_length=50, null=True) loginurl = models.CharField(max_length=100, null=True) weight = models.IntegerField(null=True) level = models.CharField(max_length=20, choices=LEVEL, null=False) class Student(models.Model): epicenter_id = models.CharField( null=False, blank=False, unique=True, max_length=10 ) last_name = models.CharField(null=False, max_length=50) first_name = models.CharField(null=False, max_length=50) email … -
How to populate my heroku postgres database on Windows with db.sqlite3?
I have been stuck in a bit of a predicament where I had a working django server through Heroku for over a year. But then tried to redeploy now that I am on a Windows instead of Linux and have not been able to get things working again. The app is deploying properly and the postgres database is properly migrated and has all the correct tables. However, the tables are all empty. And I can not figure out a way to get the database populated like it had been before. I am filling up a db.sqlite3 database with csvs like this: # import allgifts with open(os.path.abspath(os.path.dirname(__name__)) + '/static/csvs/AllGifts.csv') as f: reader = csv.reader(f) for row in reader: _, created = AllGift.objects.get_or_create( giftId=row[0], title=row[1], productUrl=row[2], imageUrl=row[3], price=row[4], minAge=row[5], maxAge=row[6], gender=row[7], popularity=row[8], prime=row[9], nsfw=row[10], ) And this database still works great locally. But I am missing a step that gets this data onto heroku and I have been spinning in circles trying to find out how. Does anyone have any ideas for what I am missing? If not what is the best way for me to remedy this situation and get my database onto the server in one form or another. Thanks! -
How to order a Django query set, when only want one observation at the end?
I have a observation, "Other" that I want at the end of a queryset of other objects. However, if I order it alphabetic or any other way, "Other" comes in the middle. How do I make "Other" last? Queryset.objects.order_by('-names_of_objects') "sdnlks", "dklnldsk", "Other", "dfsdno", "cdksnodi", "cjsdkc" Instead I want: "sdnlks", "dklnldsk", "dfsdno", "cdksnodi", "cjsdkc", "Other" I don't care about the other objects order. -
How to access my python virtual env in vscode terminal
I've created a virtualenv for my django project. And i want to use vscode. But 'workon env_name' is not working in vscode terminal, but its working fine on my command prompt. -
Adding a new drop down menu item in django model field
I have a model field that is a foreign key. It shows as a drop down on the form based on the values in the table. I want to add another item in it saying 'Add New' that when selected, should open up a modal form. Could anybody please help on how to achieve this? models.py: class Agent(models.Model): agent_phone = models.CharField(max_length=15, null=True, blank=True) agent_desc = models.TextField(null=True, blank=True) agency = models.ForeignKey(Agency, on_delete=models.CASCADE, null=True) forms.py: class AgentForm(forms.ModelForm): class Meta: model = Agent fields = ('agent_phone', 'agency', 'agent_desc') The 'agency' field on the form is populated with rows in the 'Agency' table in a drop down. I want to add another item 'Add new' that should open up a form to add new agency or add a 'Add New' link on the side of drop down that should open up the Add form. Could anybody please advise how to achieve this? -
Implementing A Directory in Django Mezzanine
I'm fairly new to Mezzanine. I'm creating a website for a non profit organization. Mezzanine offers most of the requirements except a directory. What is the best way of implementing a directory of businesses? Their model are laid out as follows: class BusinessCategory(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Business(Page): name = models.CharField(max_length=50) about = models.CharField(max_length=300, blank=True) location = models.CharField(max_length=100, blank=True) category = models.ForeignKey("BusinessCategory") cover = models.ImageField(upload_to="businesses", blank=True) website = models.URLField(blank=True) phone_number = models.CharField(max_length=10, blank=True) hours = models.CharField(max_length=50, blank=True) days = models.CharField(max_length=50, blank=True) email = models.EmailField(blank=True) def __str__(self): return self.name Any advice as to the ideal way of implementing this? -
filter results from database by user_id
Hello All I have been trying for days to solve this issue, however I am really not sure where my error is. I am new to django and have been coding for a year. I have a model portfolio that takes in tickers and also linked to the user via a foreign key. In my models class Portfolio(models.Model): ticker = models.CharField(max_length=15) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='investor', null=True) def __str__(self): return self.ticker my form is as such: class PortfolioForm(forms.ModelForm): class Meta(): model = Portfolio fields = ['ticker'] def __init__(self, user, *args, **kwargs): super(PortfolioForm, self).__init__(*args, **kwargs) self.fields['ticker'].queryset = Portfolio.objects.filter(user=user) and in my views: if request.method == 'POST': form = PortfolioForm(request.POST or None, request.user) if form.is_valid(): ticker = form.save(commit=False) ticker.user = request.user ticker.save() return redirect('/add_stock') else: ticker = Portfolio.objects.filter(pk = request.user.id) output = [] for ticker_item in ticker: output.append(str(ticker)) return render(request, 'test_app/add_stock.html', {'ticker':ticker, 'output':output}) I want the user to add stocks to the Portfolio database but only return the stock tickers they added. Currently the stocks are being added to the database but nothing is returned to the user. Also stocks added to the database are available for any user to see not just the specific logged in user. I have added @login_required … -
Multiple inputs with same name to write to database
I have a form and with several fields with the same name, I need to get this data in django view and write to the database. For now I am just trying to get the HTML data and render in the view but only the last value of the html form is displayed. View def agenda_padrao(request): inicio = request.POST['inicio'] fim = request.POST['fim'] idempresa = request.POST['id'] if request.POST: for i in inicio: print(i) return render(request, 'core/agenda.html') agenda.html <form method="POST" action="/agenda/padrao/">{% csrf_token %} <div class="modal-body"> <div class="row "> <h3>Horários</h3><br/> <a class="btn btn-success" href="javascript:void(0)" id="addInput"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> </a> </div> <div id="dynamicDiv"> <div class="row col-12"> <input type="time" class="form-control form-control" id="inicio" name="inicio[]" style="width: 150px; margin-right: 10px;"> <input type="time" class="form-control form-control" id="fim" name="fim" style="width: 150px;"> <input type="hidden" name="id" value="{{ user.id_empresa }}"> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button> <button type="submit" class="btn btn-primary" >Confirmar Horário Padrão</button> </div> </form> Javascript adding the fields $(function () { var scntDiv = $('#dynamicDiv'); $(document).on('click', '#addInput', function () { $('<p>'+ '<input type="time" class="form-control form-control" id="inicio" name="inicio" style="width: 150px; margin-right: 10px;">'+ '<input type="time" class="form-control form-control" id="fim" name="fim" style="width: 150px; margin-right: 10px;">' + '<a class="btn btn-danger" href="javascript:void(0)" id="remInput">' + '<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>' + '</a><br/>'+ '</p>').appendTo(scntDiv); return false; }); … -
Loading python envvars without using `source`
I am looking for a solution to loading an envvars.sh file within a django application. I would prefer to do this within the settings module and keep a file outside of it. Here is what I currently have: SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) def source_envvars(fname='envvars.sh'): """Equivalent of `$ source {fname}` with lines in the form of `export key=value`""" envvars = os.path.join(SITE_ROOT, fname) if not os.path.exists(envvars): return with open(fname, 'r') as f: for line in f: if line.startswith('export '): line = line.strip() key = line.split('=')[0].split()[1] value = line.split('=')[1].strip('"\'') os.environ[key] = value if not os.environ.get('DB_HOST'): source_envvars() # rest of settings.py file... Are there any downsides of using this approach? I know this doesn't support complicated bash-type exports, but all I have are basic exports of the form: export DB_HOST=rds.amazon.com/12345 Does the above approach properly instantiate all the variables, or does it seem to be missing something or insecure in some way or other? -
Django/React deployment not serving static files on Heroku
I've hunted the Internet and manu SO posts but haven't found what solves my solution yet. I have a Django back end, and a React front end created with create-react-app. But all I'm getting is Django Rest Framework API Root page—from what I can tell, it's simply not serving up the static files properly. My files are located at https://github.com/acd37/lead-manager It would be a lot for me to copy and paste—but I'm hoping someone can look at this and see what the issue is, or will clone it and give it a shot. If I npm run build and then serve, I get a blank page saying that my this.props.leads.map function can't fun. If I run heroku local, I get the same API Root page. Any ideas!? New to Python——deploying NodeJS apps to Heroku is MUCH easier! -
Django group by for reverse relationship
Let's say I have the following: class A: .... class B: a = models.ForeignKey(A,....) class C: a = models.ForeignKey(A,....) b = models.ForeignKey(B,....) user = models.ForeignKey(User, ....) I want to use regroup to display all C objects grouped together by a, user in a table with fields from A and all C objects in a drop down upon clicking the row. So.... # regroup A queryset by C foreign key and user foreign key c.field1, c.field2, ...., user.email, user.first_name, .... + dropdown a.field1, a.field2, a.field3, ..... If C contains a foreign key to a with multiple users these should be distinct rows. Meaning.... First level regroup by model C... great we have C model with all related A model as drop down..... But, these can have duplicate users. So separate top level by user + C model relation. I'm lost on how to do the previous sentence. First level group by is easy.