Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django User model foreign key
I'm struggling writing a relational database in Django. Basically what I am trying to achieve is to create a user foreign key to one of the tables. I found plenty of similar questions over here but for some reason, it doesn't seem to work on my cause, maybe it's because of the version or I don't know. This is my model: from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) and for autenthification I used the build-in functionality path('api-auth/', include('rest_framework.urls')), and this is the error that I get: IntegrityError at /category/ NOT NULL constraint failed: category_category.user_id Request Method: POST Request URL: http://127.0.0.1:8000/category/ Django Version: 2.2.5 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: category_category.user_id Exception Location: C:\Users\Terkea\Anaconda3\envs\django_api_template\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383 Python Executable: C:\Users\Terkea\Anaconda3\envs\django_api_template\python.exe Python Version: 3.7.5 Python Path: ['C:\\Users\\Terkea\\PycharmProjects\\django_api_template', 'C:\\Users\\Terkea\\PycharmProjects\\django_api_template', 'C:\\Program Files\\JetBrains\\PyCharm ' '2019.2.3\\plugins\\python\\helpers\\pycharm_display', 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template\\python37.zip', 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template\\DLLs', 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template\\lib', 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template', 'C:\\Users\\Terkea\\Anaconda3\\envs\\django_api_template\\lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2019.2.3\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Wed, 11 Dec 2019 08:08:11 +0000 -
Django Rest Framework - model's parent is None when accessed through serializer
Say, I have a Testimony model that has built-in User model as foreign key like this: class Testimony(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, blank=True) description = models.TextField() With a straightforward serializer like this: class TestimonialSerializer(serializers.ModelSerializer): user = profile_serializer.ProfileGeneral(source='user.profile') class Meta: model = Testimony fields = ('description', 'user') I am making a test on the CRUD API with a setup like this: class ATest(TestCase): def setUp(self) -> None: user1 = User.objects.create_user('user1', 'email1@email.com', '2424') Testimony.objects.create(user=user1, description="desc 1", is_active=True, order=3) The strange thing is, when I try to print testimony.user, it returns nice: t = Testimony.objects.latest('pk') print(t.user) >>> User1 But if I insert the t into the serializer, I got none: TestimonialSerializer(t).data >>> OrderedDict([('description', 'desc 5'), ('user', None)]) I know I may messed things up when I write source inside my serializer. But I think the user key should show something instead of None. Even stranger, on production, it seems that the user returns the data correctly. But on testing it just returns None. -
Django and HTML: Problem with Extra Space Around Navigation Bar
I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip. I am facing a problem. There is extra space at the top and bottom of the navigation bar. How can I remove this extra white space on top and bottom of the navigation bar? I tried modifying the style codes. But I haven't managed to fix the issue. Here are my codes in triplist.html: <!DOCTYPE html> {% extends 'base.html' %} {% load static %} <html lang="en"> <link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}"> <head> <meta charset="UTF-8"> {% block title%}Trip list{% endblock %} <title>Trip list</title> </head> <body> {% block content %} <!--Page content--> <h1>Upcoming Trips</h1><br> <ol> {% for trip in all_trips %} <li><a href="{% url 'trips:activity' trip.slug %}">Trip name: {{ trip.trip_name }}</a></li> <b>Date:</b> {{ trip.date }}<br> <b>Planner:</b> {{ trip.planner_name }}<br> <b>Coplanners:</b> … -
gunicorn.service: Failed with result 'exit-code'
In my projects root folder there should be project.sock file, but I can't create it because of following error: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2019-12-11 07:32:45 UTC; 5s ago Main PID: 7302 (code=exited, status=203/EXEC) Dec 11 07:32:45 challengers systemd[1]: Started gunicorn daemon. Dec 11 07:32:45 challengers systemd[1]: gunicorn.service: Main process exited, code=exited, status Dec 11 07:32:45 challengers systemd[1]: gunicorn.service: Failed with result 'exit-code'. -
Integrity error on sumbit form in django?
I am new to django I am having a 8 rooms in the bootstrap cards and then a form to submit one user can select one room only so I wrote my models as the rooms model consisting of data and I get that data in html page rooms.html and it is working properly but on select that one card i.e the selected roomid should go as a value of hidden input in my form how should I achieve this? class rooms(models.Model): id = models.IntegerField(primary_key=True) image = models.ImageField(upload_to='images') content = models.CharField(max_length=50,default='0000000') class users(models.Model): email=models.CharField(max_length=50,default='0000000') password=models.CharField(max_length=50,default='0000000') room = models.ForeignKey(rooms,on_delete=models.CASCADE) My form template div class="card-body"> <form action="{% url 'car:user_register' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" name="username" class="form-control" required> </div> <div class="form-group"> <label for="room"></label> <input type="hidden" name="room" class="form-control" value="{{i.id}}" required> </div> <div class="form-group"> <label for="email">Email</label> <input type="text" name="email" class="form-control" required> </div> <div class="form-group"> <label for="password2">Password</label> <input type="password" name="password" class="form-control" required> </div> <input type="submit" value="Register" class="btn btn-secondary btn-block"> </form> And in views.py def user_register(request): if request.method == 'POST': room = request.POST["room"] username=request.POST["username"] email = request.POST['email'] password = request.POST['password'] user = users( password=password,email=email) user.save() return render(request,'home.html') Error is:IntegrityError at /car/user_register/ -
Not able to create a text file in Python - Django production deployment
I am new to Django deployment and created a basic Django app using a Linux server and Apache. I am using Django Rest Framework and POSTMAN wherein I want to insert an image via POSTMAN and save the name of the image in a text file. However, when I deployed my app and tested this, it doesn't seem to work. The image gets saved in my directory but the text file does not get created. This is what I had done so far: views.py: class ImageAPI(APIView): parser_classes = (MultiPartParser,) #retrieving the text file using GET method def get(self, request): image_file = pathlib.Path("data.txt") if image_file.exists(): with open('data.txt') as json_file: data = json.load(json_file) if data: return Response(data, status=200) return Response({"name" : None}, status = 400) else: return Response({"name" : "No image found"}, status = 400) #storing the image in a text file using POST method def post(self, request): file = self.request.data img_file = file['image'] if img_file: uploaded_file = img_file image = [{"name": uploaded_file.name}] with open('data.txt', 'w') as outfile: json.dump(image, outfile) serializer = ImageSerializer(image, many = True).data return Response(serializer, status = 200) else: return Response("Image isn't uploaded", status = 400) serializers.py: from rest_framework import serializers class ImageSerializer(serializers.Serializer): image_name = serializers.CharField() As stated above, … -
Boolean not right value in admin page
I have django 2.2.6 and in my model I use boolean value legacy = models.BooleanField(verbose_name='Responsable') but when I open my admin page I display the wrong value (the opposite value). In my DB the value is right but in the admin page I have the checkbox checked instead of not (for instance) What is wrong ? Thanks -
How to query django models for complex models like this
I have django model i need to create view to get data from the appointment model like appointment bkngfor_first_name, bkngfor_last_name, phone_number. I am trying to create view using this model to get that data. class appointment(models.Model): BOOKING_TYPE_CHOICE = ( ('slf', 'Self'), ('oth', 'Other') ) BOOKING_SOURCE_CHOICE = ( ('web', 'Web App'), ('mob', 'Mobile App'), ('ph', 'Phone Call'), ('vis', 'Visit') ) booking_type = models.CharField(max_length=4, choices=BOOKING_TYPE_CHOICE, default='slf') bookedon_date =models.DateTimeField(auto_now_add=True, null=True, blank=True) meeting_date = models.ForeignKey(av_booking_summary, on_delete=models.CASCADE, null=True, blank=True) phone_number = models.BigIntegerField(null=True, blank=True) time_slot = models.DecimalField(max_digits=5, decimal_places=2) purpose = models.CharField(max_length=20, default='personal consultancy') bkngfor_relation = models.CharField(max_length=10, null=True, blank=True) bkngfor_first_name = models.CharField(max_length=15, null=True, blank=True) bkngfor_last_name = models.CharField(max_length=15, null=True, blank=True) booking_source = models.CharField(max_length=50, choices=BOOKING_SOURCE_CHOICE, default='') is_active = models.SmallIntegerField(default=1) is_closed = models.BooleanField() notes = models.CharField(max_length=500, null=True, blank=True) created_by = models.IntegerField(default=0) created_on = models.DateTimeField(auto_now=True) modified_by = models.IntegerField(default=0) modified_on = models.DateTimeField(auto_now=True) @property def get_html_url(self): if self.time_slot >= 12.0: hour_format = 'PM' else: hour_format = 'AM' return f'<p class="no-text-decoration text-dark font-small font-bold mt-0 mb-0">{self.time_slot} {hour_format}</p>' @property def get_appointments_list(self): if self.time_slot >= 12.0: hour_format = 'PM' else: hour_format = 'AM' if self.phone_number == None: return f'<div class="row striped daily-appointment-list text-dark font-bold">'\ f'<div class="col s2"> {self.time_slot} {hour_format}</div>'\ f'<form><div class="col s3"><input type="text" name="phone_number"></div>'\ f'<div class="col s6">'\ f'<div class="row"><div class="col s6 pl-0"><input type="text" name="first_name"></div>' \ f'<div … -
import django models with ForeignKeyWedget
I have 3 models (Projects,Sites, Devices). And I try to import devices and configured with ForeignKeyWedget to link Project and Sites by name (not pk). When I try to import with csv file, I don't see any error and I don't see the new devices in the device list. Can advise if anything missing or wrong? Thanks models.py class Projects(models.Model): Name = models.TextField(blank=False,default="Project Name") StartDate = models.TextField(blank=False,default='dd/mm/yyyy') EndDate = models.TextField(blank=False,default='dd/mm/yyyy') def __str__(self): return '{0}'.format(self.Name) class Sites(models.Model): Name = models.TextField(blank=False, default="Site Name") Project = models.ForeignKey(Projects,on_delete=models.CASCADE) def __str__(self): #return 'SiteName:{} ---------------Country:{}'.format(self.Name, self.Country) return '{0}'.format(self.Name) class Devices(models.Model): Name = models.TextField(blank=False, default='DeviceName') IP = models.TextField(blank=False, default='x.x.x.x') Project = models.ForeignKey(Projects,on_delete=models.CASCADE) Site = models.ForeignKey(Sites,on_delete=models.CASCADE) def __str__(self): return '{0}'.format(self.Name) resources.py from import_export import resources, fields from import_export.widgets import ForeignKeyWidget from .models import * class DeviceRecources(resources.ModelResource): Project = fields.Field( column_name='Project', attribute='Project', widget=ForeignKeyWidget(Projects, 'Name')) Site = fields.Field( column_name='Site', attribute='Site', widget=ForeignKeyWidget(Sites, 'Name')) class Meta: model = Devices fields = ('Name','IP','Category','Project', 'Site','id') view.py def upload(request): if request.method == 'POST': devices = resources.modelresource_factory(model=Devices)() dataset = Dataset() new_devices = request.FILES['myfile'] imported_data = dataset.load(new_devices.read().decode('utf-8'),format='csv') result = devices.import_data(dataset, dry_run=True) # Test the data import if not result.has_errors(): print('No errorrrrr') print(dataset) devices.import_data(dataset, dry_run=False) # Actually import now return redirect(devicesview) else: return render(request,'import.html') Debug output enter image … -
'str' object is not callable when i am trying to delete from Django admin interface?
getting this error when i am trying to delete from django admin panel TypeError at /admin/carts/cart/21/delete/ 'str' object is not callable Request Method: GET Request URL: http://localhost:8000/admin/carts/cart/21/delete/ Django Version: 2.2.6 Exception Type: TypeError Exception Value: 'str' object is not callable Exception Location: C:\Users\HP\spippt\ppt\lib\site-packages\django\db\models\deletion.py in collect, line 224 Python Executable: C:\Users\HP\spippt\ppt\Scripts\python.exe Python Version: 3.7.0 Python Path: ['C:\Users\HP\spippt\ppt\myproject', 'C:\Users\HP\spippt\ppt\Scripts\python37.zip', 'C:\Users\HP\spippt\ppt\DLLs', 'C:\Users\HP\spippt\ppt\lib', 'C:\Users\HP\spippt\ppt\Scripts', 'C:\Users\HP\AppData\Local\Programs\Python\Python37-32\Lib', 'C:\Users\HP\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\HP\spippt\ppt', 'C:\Users\HP\spippt\ppt\lib\site-packages'] Server time: Wed, 11 Dec 2019 12:14:29 +0530 -
Memory leak in Django Server?
I am running daphne server on production. I am running 8 python processes on same machine, each on different ports. Problem is that the memory used by each process keeps on increasing over time from 2.5% on start to 11-12% after 12 hours. After sometime, the process restarts as well. Is this general behavior or am I missing something? output of top after 1 hour 15623 root 20 0 5202920 337408 50704 S 50.5 4.6 21:52.55 daphne 15624 root 20 0 5024892 335028 50344 S 30.2 4.6 22:21.99 daphne 15726 root 20 0 5111504 334544 50656 S 42.2 4.6 24:45.48 python 15626 root 20 0 5091180 332068 50224 S 33.2 4.5 22:40.56 daphne 15627 root 20 0 5143132 327988 50176 S 32.6 4.5 21:50.83 daphne 15625 root 20 0 5092620 320452 49908 S 29.2 4.4 20:50.55 daphne I am using supervisor, daphne, django-channel, django-rest-framework. Is there a way to detect when is this memory leak happening, if this is a memory leak. -
How could I save my input from a check box wherein when I check only one option on the box it gave me an error
How could I save my input from a check box wherein when I check option1 of the box and save it it gives me an error saying there is no value on option2 or vice versa. But when i marked them both. I was able to save it on the database, problem is on my database it should only show either value of 1 or 0 and null if there is no input. 1 if its regular and 0 if its special and if either of them has input the other one should be null. Here is my html code for now. <div class="col-md-6"> <div class="form-group bmd-form-group"> <input type="checkbox" name="is_regular" value="1"> Regular<br> <input type="checkbox" name="is_special" value="0"> Special<br> </div> </div> Model forms class Save_Holiday_Form(ModelForm): class Meta: model = Holiday fields = ['holiday_id', 'holiday_name', 'is_regular', 'is_special', 'date_start', 'date_end'] Views.py def add_holidays(request): holiday_name = request.POST['holiday_name'] date_start = request.POST['date_start'] date_end = request.POST['date_end'] is_regular = request.POST['is_regular'] is_special = request.POST['is_special'] holiday_info = Holiday( holiday_name=holiday_name, date_start=date_start, date_end=date_end, is_regular=is_regular, is_special=is_special ) holiday_info.save() return render(request, 'holidays.html') -
How to access views written in mongodb using mongoengine?
In one of my project, I'm using mongoengine 0.9 and pymongo 2.8 for the database and python django as a framework. I came through the view concept in mongodb and created a view in the database for a model named User. I can access the data from User model like in the code below added. But I don't know how to access the view from mongodb using mongoengine. Anyone have any suggestion, please help? user_list = User.objects(active=True) -
Django - get user id after saving the user
I'm working on a project using Python(3.7) and Django(2.2) in which I have implemented models for multiple type of users and combined models by using MultiModleForm to display as a single form on front end, after that when I try to create a user in view and call the save method for user model and try to get its id but it's giving an error. Here's what I have tried so far: From models.py: class Parent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) contact_email = models.EmailField(blank=False) customer_id = models.BigIntegerField(blank=False) contact_no = PhoneNumberField(blank=True, help_text='Phone number must be entered in the' 'format: \'+999999999\'. Up to 15 digits allowed.') collection_use_personal_data = models.BooleanField(blank=False) From forms.py: class ParentForm(forms.ModelForm): class Meta: model = Parent fields = ('contact_email', 'contact_no', 'collection_use_personal_data') class UserParentForm(MultiModelForm): form_classes = { 'user': UserForm, 'profile': ParentForm } From views.py: def post(self, request, *args, **kwargs): print(request.POST) user_type = request.POST.copy()['user-user_type'] form = None if user_type == 'PB': form = UserBelow18Form(request.POST) elif user_type == 'PA': form = UserAbove18Form(request.POST) elif user_type == 'Parent': form = UserParentForm(request.POST) print('user-parent form selected') elif user_type == 'GC': form = UserGCForm(request.POST) if form.is_valid(): user = form['user'] profile = form['profile'] if user_type == 'Parent' or user_type == 'GC': c_id = generate_cid() profile.customer_id = c_id print('id generated for … -
I am trying to insert data into db from Django view file. No error but data is not saving into db
I am trying to insert data into DB from a Django view file. No error but data is not saving into DB. I am trying scrape data from flipkart page, it is not showing any error but data is not saving into db def scrape_view(request): session=requests.Session() my_url="https://www.flipkart.com/mobiles/pr?sid=tyy%2C4io&p%5B%5D=facets.brand%255B%255D%3DRealme&otracker=nmenu_sub_Electronics_0_Realme&sort=price_asc" #link which I want t scrape uclient=session.get(my_url,verify=False).content page_soup=soup(uclient,"html.parser") containers=page_soup.findAll("div",{"class":"_3O0U0u"}) for container in containers: product_name=container.div.img["alt"] price_container=container.findAll("div",{"class":"_1vC4OE _2rQ-NK"}) price=(price_container[0].text) rating_container=container.findAll("div",{"class":"hGSR34"}) rating=rating_container[0].text new_redmi=Redmi_Mobiles() new_redmi.model_name=product_name new_redmi.price=price new_redmi.rating=rating new_redmi.save() return redirect('home') #models.py class Redmi_Mobiles(models.Model): model_name=models.CharField(max_length=200) price=models.CharField(max_length=10) rating=models.FloatField() def __str__(self): return self.model_name -
Cannot run migration command for django
I'm trying to practice and learn django to create a webapp and when I run the "python manage.py migrate" command, I get this error "django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")". What is the possible cause and how can it be fixed? -
I am getting (Cannot assign "11": "Notification.user_to_notify" must be a "User" instance.) in Django
Below is my code. I have 2 models Post and Notification. Whenever any user likes any post i am adding that to notifications tables. and getting 'Cannot assign "11": "Notification.user_to_notify" must be a "User" instance.' this error. #Post model class Post(models.Model): title = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='images/',blank=True) posted_by = models.ForeignKey(User, on_delete=models.CASCADE) #Notification model class Notification(models.Model): user_to_notify = models.ForeignKey(User, related_name = 'user_to_notify',on_delete=models.CASCADE) user_who_fired_event = models.ForeignKey(User, related_name= 'user_who_fired_event' ,on_delete=models.CASCADE) event_id = models.ForeignKey(Event, on_delete=models.CASCADE) seen_by_user = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) postExists = Post.objects.get(pk=post_id) # posted_by is having relation with User notification = Notification() notification.user_to_notify = postExists.posted_by.id(ERROR) #also tried notification.user_to_notify = postExists.posted_by(Still getting ERROR) -
Field return count of another table
I need that read_booksfield (in Purchased), return the Rating objects count. Should return the number of objects according to the filter of the same collections of each book in Rating and the same user. I don't know how to do this because Rating and Purchased are not directly dependent. rating/models.py class Rating(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) book = models.ForeignKey(Statement, on_delete=models.CASCADE, null=False) rating = models.IntergerField(default=0) book/models.py class Books(models.Model): collection = models.ForeignKey(Collection, on_delete=models.DO_NOTHING, blank=True, null=True) book = models.CharField(max_length=250, blank=True, null=True) collection/models.py class Collection(models.Model): title = models.CharField(max_length=50) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) purchased_collections/models.py class Purchased(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) collection = models.ForeignKey(Collection, on_delete=models.DO_NOTHING) date = models.DateTimeField(default=datetime.now) read_books = models.IntegerField(default=0) -
How to Aggregate QuerySet for Arbitrary Keys Group By
<QuerySet [ {'id': 520, 'Commission': None, 'Effective Date': '2019-12-11 00:00:00+00'}, {'id': 520, 'Commission': 30, 'Effective Date': None} ]> Suppose I had a Django QuerySet like the above, with an arbitrary number of matching keys where only one is expected to not be null per key. How do I get a result like the following per id as if I'm grouping by id? <QuerySet [ {'id': 520, 'Commission': 30, 'Effective Date': '2019-12-11 00:00:00+00'} ]> -
Django models.ImageField does not validate image file (data sent by axios)
I'm using Django as my backend and React as my front. I want the users to be able to upload their photos, and I managed to do that recently. This is how the users send their photo in the front. addUserImage = (Image, id) => (dispatch) => { axios.post(`/api/${id}/image`, Image, { headers: { 'Content-Type': 'multipart/form-data', }, }) .then((res) => { console.log(res.data); }) .catch((err) => { console.log(err); alert('Your image file is not valid. Please check again.'); }); }; onChange = (e) => { if (e.target.files.length !== 0) { if (e.target.files[0].size > 50000000) { alert(`'${e.target.files[0].name}' is too large, please pick a smaller file`); } else { this.setState({ selectedImage: e.target.files[0] }, () => { const formData = new FormData(); formData.append( 'Image', this.state.selectedImage, ); //this.props.onUploadPhoto calls addUserImage from above. this.props.onUploadPhoto(formData, this.props.selected_object.id); }); } } } <Button variant="contained" component="label" > <input type="file" id="image" accept="image/png, image/jpeg, image/pjpeg, image/gif" onChange={this.onChange} style={{ display: 'none' }} /> Upload An Image! </Button> This code manages to show normal images successfully. However, I'm worried that some users might just upload fake image files(e.g. Forcefully changed extensions). I heard that Django's models.ImageField performs image validation. This is my related backend code. //views.py def post_photo(request, id): if request.method == 'POST': if request.user.is_authenticated: try: … -
Export file to csv but when it wont show the file in django
So i try to export result of query into csv files, but when i do , it says success , but i dont see where is the file , or the file being download in the browser , i already search the file but i dont find it anywhere, here's the code AJAX in html <script> $(document).ready(function() { $("#export").click(function () { var urls = "{% url 'polls:export' %}"; var name = $('#columnselect').val(); var table = $('#dataselect').val(); var column = $('#conditionselect').val(); var operator = $('#operator').val(); var condition = $('#parameter').val(); $.ajax({ url: urls, data: { 'name' : name, 'table': table, 'column' : column, 'operator' : operator, 'condition' : condition }, success: function(data) { alert("success"); }, error: function(data) { alert("error occured"); } }); }); }); </script> urls.py path('export/',views.export,name='export'), views.py def export(request): import cx_Oracle data_name = request.GET.get('name',1) table_name = request.GET.get('table',1) column_name = request.GET.get('column',1) operator = request.GET.get('operator',1) condition = request.GET.get('condition',1) dsn_tns = cx_Oracle.makedsn('IP', 'PORT', sid='') conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns) c = conn.cursor() c.execute("select "+data_name+" from "+table_name+" where "+column_name+operator+"'"+condition+"'") c.rowfactory = makeDictFactory(c) columnalldata = [] for rowDict in c: columnalldata.append(rowDict[data_name]) context = { 'obj4' : columnalldata } response = HttpResponse(content_type ='text/csv') response['Content-Disposition'] = 'attachment;filename="output.csv"' writer = csv.writer(response) writer.writerow(context) print(response) return response can someone find where … -
Can't GET user information with token using django-rest-knox TokenAuthentication
I'm a bit of a newbie to Django and authentication (I'm loosely following this tutorial) and I've searched all over and can't find anything that has helped me fix this problem. I'm using django-rest-knox to generate authorization an token(s) for a user and then attempting to send the token back (using Postman) to GET the user's information (id, username, and email) in a response from the server. I can get the tokens fine using my LoginAPI class, but when I try to pass the token back in a GET request to my UserAPI class, I get a 401 response with the following body: { "detail": "Authentication credentials were not provided." } Postman Screenshot Code from my python files is below. Any help is much appreciated. urls.py from .api import LoginAPI, UserAPI from django.urls import path, include urlpatterns = [ path('api/auth/login/', LoginAPI.as_view()), path('api/auth/user/', UserAPI.as_view()), path('api/auth/knox/',include('knox.urls')), ] api.py from rest_framework import permissions, generics, authentication from rest_framework.response import Response from knox.models import AuthToken from .seralizers import UserSerializer, LoginSerializer # Login API class LoginAPI(generics.GenericAPIView): permission_classes = [permissions.AllowAny, ] serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) # Get User … -
Django: Which one do you recommend? I have to replace django-facebook library
I have to replace django-facebook library. I thought I use social-auth-app-django libaray or python-social-auth ver0.2.1. I heard social-auth-app-django library can be used on Django version more than 1.8. But problem is django version is 1.8. I wonder which one choice is more wise. 1. Upgrade Django version 1.8 to 1.1 . 2. Replace django-facebook library to python-social-suth ver0.2.1 . Help :( -
How to leave a radio button selected by default according to a Django field?
File models.py: class AbstractRating(models.Model): stars = models.PositiveSmallIntegerField() user = models.ForeignKey(User, on_delete = models.CASCADE) content = models.TextField() created = models.DateTimeField(auto_now_add = True) class Meta: abstract = True class Rating(AbstractRating): course = models.ForeignKey(Course, on_delete = models.CASCADE) class Meta: verbose_name = 'calificación del curso' verbose_name_plural = 'calificaciones del curso' def __str__(self): return self.course.title I am trying to make a star rating system, the stars are defined in the stars field, the problem occurs at the moment of updating any instance of the Rating model. I need to leave a radio button selected by default (checked) according to the value of the stars field, but I don't know how to do it. Basically the problem is to set the attribute marked on the correct radio button. But I do not know how to do it. You may have to use templates tags, but I don't know how to do it, I already tried. Any solution? File HTML: <div class="rating-stars"> <input type="radio" name="stars" value="1" id="1"> <input type="radio" name="stars" value="2" id="2"> <input type="radio" name="stars" value="3" id="3"> <input type="radio" name="stars" value="4" id="4"> <input type="radio" name="stars" value="5" id="5"> </div> File views.py: class RatingUpdateView(LoginRequiredMixin, CheckCourseOwnerAndRatingMixin, UpdateView): model = Rating form_class = RatingForm template_name = 'ratings/rating_update_form.html' success_url = reverse_lazy('courses:list-of-user') def … -
Django NoReverseMatch using views parameter
i am doing a inventory app and i have included actions(CRUD) to perform on the saved items. However when a click on 'dispatch' i get this error, NoReverseMatch at /inventory Reverse for 'dispatch' with arguments '('hhe/ge/3.009/67-8',)' not found. 1 pattern(s) tried: ['dispatch/(?P[^/]+)$'] hhe/ge/3.009/67-8 is one of model_numbers. dispatch_view in views.py def dispatch_view(request,model_number): if request.method=='POST': dispatch_item=New_asset.objects.get(model_number=model_number) form= dispatch_form(request.POST,instance=dispatch_item) if form.is_valid(): post = form.save(commit=False) post.save() return HttpResponseRedirect('/inventory') else: form = dispatch_form() return render(request, 'dispatch.html', {'form': form,'dispatch_item':dispatch_item}) url.py path('dispatch/<str:model_number>', views.dispatch_view,name='dispatch'), url(r'^inventory$', views.allassets,name='inventory'), inventory.html {% for asset in query %} <tr class="clickable-row"> <td>{{asset.asset_name}}</td> <td>{{asset.model_number}}</td> <td>{{asset.quantity_received}}</td> <td>{{asset.specification}}</td> <td>{{asset.supplied_by}}</td> <td>{{asset.department_assigned}}</td> <td>{{asset.date_received}}</td> <td><a href=" {%url 'dispatch' asset.model_number%}"><span class="glyphicon glyphicon-pencil" >Dispatch</span></a> Thanks