Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django links to the comment function in the backend does not work
After transfer the website to another server with higher python version stoped working the links in the backend to the comment function. Does somebody know where could the problem be? Thank you. -
Django, how to pass a variables from the Django admin to a template?
I want to be able to set a variable in the django admin panel, wich will be passed to the template as template variable, similar to placeholder in cms. (For exapmle when I save this variable in admin panel it will be rendered to the template) -
reusable app (package) in Django - how to add extra models
I am writing a small package that extends the django app that is used by many of my colleagues locally. So right now they can simply add it via pip, and then they add this extension in INSTALLED_APPS in settings.py. But the problem is that I can't add the new models to this extension (or at least I don't figure out yet how to do it correctly) because then the guys who would like to use my extension, have to sync their database or make migrations so their database contains the models needed for extension. Is it possible (and right thing to do) to add new models to the current django project 'silently' as soon as the user adds the app to INSTALLED_APPS? -
mysqlclient-python & security issues
I can't figure out whether I'll bear any risk in terms of malicious software & security if I download mysqlclient-python from here https://pypi.python.org/pypi/mysqlclient? Is mysqlclient-python provided in PyPI reliable in your opinion? I want to install mysqlclient in my global Python environment, not virtualenv. I've started learning Python. I want to try Django framework and Mysql database. I've already installed them. I know that PyPI is a third party repository, and everyone with a bit of experience can write and upload their package to PyPI. Is it safe to install mysqlclient, using pip and PyPI? -
Django 1.11 can we create relationship between tables from two different databases?
In my project I'm trying to create central DB service with multiple database so here my question is can we create relationship between tables from two different databases? Example: MySQL DB1.table user class User(models.Model): name = models.CharField() MySQLDb2.table post class Post(models.Model): title = model.CharField() user= models.Forignkey(User) -
make login panel without using models in django
def login(request): username=request.GET.get('uid') password=request.GET.get('upass') # print(username) # print(password) connection() query = "select * from idpassword where (U_name = '%s' & U_pass = '%s')" %(username,password) cursor.execute(query) U_id = cursor.fetchone() connect.commit() print(U_id) return HttpResponse(U_id) def connection(): try: global connect global cursor connect = mysql.connector.connect(host='localhost',database = 'advanceclasses',user = 'root',password = 'admin') cursor = connect.cursor() # print("connected!") except Error as e: print(e._full_msg) return HttpResponse("Connection is not Established !") Can you please help to solve this error? I am working with MY SQL and Django and at basic-stage. I got an error as programming-error. username: S12 and password: Sabc has already stored in table idpassword of the advanceclasses database. I want to find Unique-id of that table. Please help me -
use django_filters to filter for multiple arguments
I am using Relay, Django, Graphene Graphql. I would like to use django_filters to filter for multiple arguments of type on accommodation. This is described in my schema file and atm looks like: class AccommodationNode(DjangoObjectType) : class Meta: model = Accommodation interfaces = (relay.Node,) filter_fields = ['type'] This works perfectly if I pass a single string like: {"accommodationType": "apartment"}, but what if I want to filter for all accommodations that are apartments OR hotels? something like: {"accommodationType": ["apartment","hotel"]} This is my model: class Accommodation(models.Model): ACCOMMODATION_TYPE_CHOICES = ( ('apartment', 'Apartment'), ('host_family', 'Host Family'), ('residence', 'Residence'), ) school = models.ForeignKey(School, on_delete=models.CASCADE, related_name='accommodations') type = models.CharField( max_length=200, choices=ACCOMMODATION_TYPE_CHOICES, default='apartment' ) def __str__(self): return str(self.school) + " - " + self.type Is there any way I can do this without writing custom filters as are suggested here? For only one filter field this is a great solution but I'll end up having around 50 throughout my application including linked objects... -
How can I execute Python Django runserver command in Jupyter Notebook?
I am new for Python,Django & Jupyter Notebook. And I tried my best to search and study from StackOverflow and get the Python Django and Jupyter Notebook work together. But when I tried to execute the python manage.py runserver command in the cell and get error message such as syntax error. So can anyone help me to solve this problem. My environment is Windows 10 Pro x64 with Python 3.5 Django 2.10 Jupyter Notebook 4.0 -
Delete only some django user permission
Hi is it possible to remove all permissions only of some model. Example There is type A model permissions and type B model permission, need to clear all user permission of type A -
Many to Many relationship not working in Django REST framework
I am trying to create a simple Many to Many relationship. I have two models: IP and IPCollection, an IP can belong to 0 or more collections, and an IPCollection consists of IP addresses. After following the documentation, I thought I had got it to work. But I could not select existing IP addresses when creating a new collection in the API interface. Following this post: Lists are not currently supported in HTML input I managed to solve the problem, allowing me to create a new IPCollection while choosing between the existing IP's from a form. Everything seemed to be fine. However, once I implemented the solution provided in that stackoverflow post, a new problem occured: I can't retrieve my IPs anymore. I have my two endpoints: /ipcollections and /ips, and whenever I try to do a GET request to /ips I get the following error: TypeError at /ips/ __init__() takes 1 positional argument but 2 were given I have tried searching for a solution to this problem, but so far nothing seems to work. This is wat my serializers look like after implementing the solution from the other stackoverflow post: class IpSerializer(serializers.PrimaryKeyRelatedField, serializers.ModelSerializer): class Meta: model = Ip fields … -
How to create/update nested Serializers with Filefields
I have a python 3.6 + django 1.10 + djangorestframework 3.6.4 project. I have 2 Model classes called Report and ReportFile. I want to create the CRUD operations to get, post and put those files together with a report. 1 Report has a type (which doesn't really matter here) and can have many ReportFiles that the user should be able to upload. The modelclasses look like this: class Report(CreationModificationMixin): report_type = models.ForeignKey(ReportType, on_delete=models.SET_NULL, null=True, related_name='issues', verbose_name='Report', editable=False) name = models.CharField(max_length=50, blank=True) class ReportFile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) report = models.ForeignKey(Report, on_delete=models.CASCADE, related_name='files') uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='uploads', null=True) file = models.FileField(upload_to=upload_report_to, max_length=500) and the serializer class: class ReportSerializer(serializers.ModelSerializer): files = ReportFileSerializer(many=True) formats = serializers.SerializerMethodField() class Meta: model = Report fields = ('id', 'name', 'report_type', 'files') def create(self, validated_data): rfs_data = validated_data.pop('files') rf = Report.objects.create(**validated_data) for rf_data in rfs_data: ReportFile.objects.create(Report=rf, **rf_data) return rf and the ViewSet: class ReportViewSet(viewsets.ModelViewSet): serializer_class = ReportSerializer queryset = Report.objects.all().prefetch_related('report_type') But I cannot manage to upload the files correctly. Because first I cannot manage to upload that correctly with Postman and I somehow also doubt that this is the correct way to go. Can somebody hint me how I should do this? Thank you a lot! -
Queryset in __init__ Form Django
class PaymentSelectForm(forms.Form): date_from = forms.DateField() date_to = forms.DateField() website = ModelChoiceField() paymentmethod = forms.ChoiceField(choices=PAYCODE_CHOICES) def __init__(self, *args, **kwargs): super(PaymentSelectForm, self).__init__(*args, **kwargs) applyClassConfig2FormControl(self) self.fields['website'].queryset=Website.objects.all() I have errors: TypeError: __init__() missing 1 required positional argument: 'queryset'. How can I use Queryset in __init__ Form? -
How to paginate queryset for Serializer
I'm retreiving Category and its outfits list. My problem is there are too many outfits belong to a category. class CategoryListAPIView(generics.RetrieveAPIView): serializer_class = CategoryDetailSerializer ... class CategoryDetailSerializer(serializers.ModelSerializer): outfits = serializers.SerializerMethodField() ... class Meta: model = Category fields = ( ... 'outfits', ... ) def get_outfits(self, obj): //This is returning 39 items. // Can we paginate this? if obj.outfits is not None: return OutfitListSerializer(obj.outfits, many=True).data return None Can we paginate it so that user can first see 24 outfits and refresh to see the rest of outfits? -
How to temporarily dissable django-stronghold
How do i dissable the app django-stronghold temporarily?I want to make all my urls publicly avaiable again. Commenting out 'stronghold' in INSTALLED_APPS doesnt work. -
Posting array of objects in request in form-data in django api
I am using Django Restframework for apis. I am working on a POST api where I need to send an array of objects in form-data. When I tried it in raw data it is working perfectly. But when I use form-data in postman and placing the value in array, It is causing problem. The key value pair i am using in raw data is { "services": [ { "category_image": "", "category_name": "construction", "budget_min": "0-1000", "budget_max": "0-1000", "distance_min": "200", "distance_max": "500", "projects": [ { "category_image": "", "category_name": "residential", "sub_category": [ { "project_name": "single family", "project_image": "", "parent_id": "1" }, { "project_name": "multi family", "project_image": "", "parent_id": "1" }, { "project_name": "big family", "project_image": "", "parent_id": "1" } ] }, { "category_image": "", "category_name": "hospitality", "sub_category": [ { "project_name": "health care", "project_image": "", "parent_id": "5" }, { "project_name": "hotels", "project_image": "", "parent_id": "5" } ] } ], "sub_category": [ { "service_name": "wall", "service_image": "", "parent_id": "1" }, { "service_name": "kitchen", "service_image": "", "parent_id": "1" }, { "service_name": "outdoor", "service_image": "", "parent_id": "1" } ] }, { "category_image": "", "category_name": "driving", "sub_category": [ { "service_name": "car", "service_image": "", "parent_id": "5" }, { "service_name": "bike", "service_image": "", "parent_id": "5" } ] } ] } … -
Django import export - Unable to import model with BinaryField
I'm trying to import data for a model which has nullable BinaryField. The data doesn't contain the field and I want it to be imported with a null value in the field. If the field already exists in the database for a given id, it should keep the value as it is. I removed the field from the fields whitelist in the corresponding Resource object and added it to the exclude blacklist. However, I'm getting this error while importing - can't pickle memoryview objects. Traceback: Traceback (most recent call last): File "/lib/python3.5/site-packages/import_export/resources.py", line 451, in import_row original = deepcopy(instance) File "/lib/python3.5/copy.py", line 182, in deepcopy y = _reconstruct(x, rv, 1, memo) File "/lib/python3.5/copy.py", line 297, in _reconstruct state = deepcopy(state, memo) File "/lib/python3.5/copy.py", line 155, in deepcopy y = copier(x, memo) File "/lib/python3.5/copy.py", line 243, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "/lib/python3.5/copy.py", line 174, in deepcopy rv = reductor(4) TypeError: can't pickle memoryview objects Package versions - django==1.11, django-import-export==0.6 -
Converting Tex to mathematical formula in the web post (python django)?
I first built my personal website using CMS (WordPress). I have many posts which including some mathematical formula. A plugin for wordpress website like latexpage can easily convert the Latex into mathematical formula inside my post. Recently, I re-build my website by Python Django, and I know one way to use Latex is to code a .tex template which is to generate a whole PDF using Python and Latex: my_latex_template.tex {% autoescape on %} \documentclass{article} \begin{document} {{ content }} \end{document} {% endautoescape %} But many times, I don't need to write a whole Latex PDF. I mean I only have a few mathematical formulas inside one post which need to use Latex. Like the question post in /tex.stackexchange.com/. You just write something like $ ... $ or $$ ... $$. My question: is there some quick way to achieve this? -
Concatenation and validation of fields (Django)
I'm retrieving some fields using list(queryset.values(*fields)) and I want to concatenate two fields to export it in xlsx file and also put some validations on fields. For example for q in queryset: fields =['fname', 'lname', 'speed'] list_dict = list(queryset.values(*fields)) h = ['fname', "lname", 'speed'] generate_xl("sample", h, list_dict, request) I want to print fname+lname together and also change the header name. For example h = ['fullname', 'speed'] And also put validation on 'speed' field before exporting to xlsx file . For example speed = locale.format('%.3f', q.speed) Expected Output in xlsx : [Harry-Potter, 0.563] -
Syntax Error in SQL Query( select ) when an empty list is passed
I'm running SQL Query using python-Django RAW Query..!! I'm using IN() function to pass my tuple in the query. My code looks like this... Here I am getting the list of dnc_domains and dnc_company from a json/function dnc_domain_names = list(map(lambda x: get_domain_name(x), dnc_websites)) dnc_company_names = list(map(lambda l: l.lower(), list(filter(None, list(map(lambda x: x['company_name'], dnc_info)))))) QUERY: select_query = """ select c.id from ( select id, lower(company_name) as c_name,substring(website from '(?:.*://)?(?:www\.)?([^/]*)') as website_domain, from contacts where campaign_id = %s ) c where c.c_name IN %s OR c.website_domain IN %s """ Executing Query: with connection.cursor() as cursor: cursor.execute(select_query, (campaign.id,tuple(dnc_company_names),tuple(dnc_domain_names)) matching_contact_ids = cursor.fetchall() But, there is a case when any dnc_company_names or dnc_domain_name is empty [] then my Query throws an Error otherwise if there at least 1 element in any of them then it works fine. SQL Error: syntax error at or near ")" LINE 5: WHERE id IN () ^ So, help me to tackle this error. SQL should handle both empty or non empty tuples. -
Nothing Helps! Manager isn't available; 'auth.User' has been swapped for 'user.User'
I am trying to make a signup form and save users. I am getting this error: Manager isn't available; 'auth.User' has been swapped for 'user.User'. That's because in my settings.py the AUTH_USER_MODEL = 'user.User' instead of AUTH_USER_MODEL = 'auth.User'. I dont' want to change that because I use that in another piece of code. I saw people having this problem online aswell and they said: " you have to define User with the Custom User model and you can do this with get_user_model at the top of the file where you use User " I tried that but I still get the same error. Please help! register.html {% block content %} <h1>Signup</h1> <form class="site-form" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="register"> </form> {% endblock %} forms.py from django.contrib.auth.forms import UserCreationForm from user.models import User from django import forms from django.contrib.auth import get_user_model class UserCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = get_user_model() fields = ('email', 'name') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 … -
Django Extra Views, CreateWithInlinesView - how to get InlineFormSet pass to _form.html?
How do I get InlineFormSet to show in my building_form.html? views.py from django.contrib.auth.mixins import LoginRequiredMixin from extra_views import InlineFormSet, CreateWithInlinesView from buildings.models import Building, Gallery from .forms import BuildingForm class GalleryInline(InlineFormSet): model = Gallery fields = ['image', 'caption'] class BuildingCreateView(LoginRequiredMixin, CreateWithInlinesView): model = Building form_class = BuildingForm inlines = [GalleryInline, ] template_name = 'cms/building_form.html' forms.py from django.contrib.gis.forms import OSMWidget, ModelForm from buildings.models import Building class BuildingForm(ModelForm): class Meta: model = Building fields = '__all__' widgets = { 'point': OSMWidget( attrs={ 'map_width': 600, 'map_height': 600, 'template_name': 'gis/openlayers-osm.html', 'default_lat': 56, 'default_lon': 10, 'default_zoom': 7, } ) } class Media: css = { 'all': ( 'https://cdnjs.cloudflare.com/ajax/libs/ol3/3.20.1/ol.css', 'gis/css/ol3.css', ) } js = ( 'https://cdnjs.cloudflare.com/ajax/libs/ol3/3.20.1/ol.js', 'gis/js/OLMapWidget.js', ) building_form.html {% block content %} <form enctype="multipart/form-data" method="post" action=""> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"/> </form> {% endblock %} -
Django static files in Development not working
I have the following directory structure in my project: I'm trying to serve the static files in my environment, but I always getting the 404 error. This is my settings.py configuration: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) I also put this in my urls.py: URLS: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() And this is my view: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Tell the browser to be responsive to screen width --> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- Favicon icon --> <link rel="icon" type="image/png" sizes="16x16" href="../assets/images/favicon.png"> <title>Nossas Finanças</title> <!-- Bootstrap Core CSS --> <link href="{% static 'plugins/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> I've follow a lot of tutorials but I don't know what i'm doing wrong. I know by this question (Django Static Files Development) that the static files are served in two different way when is in Dev and in production. Someone can help me? -
Is it possible to install mysqlclient (DB API driver) without using pip and PyPI?
I've been learning Python. I've installed Mysql database downloaded from the official website.I have Django framework installed through downloading it from the official website https://www.djangoproject.com/download/. Now I need mysqlclient (DB API driver). I've learned of possible security risks as to using pip and PyPI. The widely used pip package management system, which most Python developers rely on, doesn't require cryptographic signature before executing code when a package is installed. PyPI is a third party repository. According to PyPI officials (the article as of 9/16/2017), PyPI does not have any full time staff devoted to it. It is a volunteer run project with only two active administrators. As such, it doesn't currently have resources for some of the proposed solutions such as actively monitoring or approving every new project published to PyPI. On Septermber 16, 2017, there came some news about some Malicious Libraries uploaded into PyPI. My question is how to installmysqlclient needed in the context of Python, Django and Mysql database, without using pip and PyPI repository? -
Restful API optimization to get huge data
I have a page for listing categories. There are parameters under categories and sub-parameters under parameters and data is huge. Recently I developed and tested the same. It is taking a lot of time and the performance is severely hit. Because there are about 1600 API calls(API calls to fetch the data for each of the categories, parameters & sub-parameters) for that single page. I have two questions. 1) Which way is effective? a or b? a) I have an API to get data for a parameter, so that I can make use of this call 1600 times to get data for all categories/parameters/sub-parameters. b) Have one call to get all parameters/parameters/sub-parameters data 2) Does AWS charge based on number of the calls? -
OSError: [Errno 12] Cannot allocate memory
I have implemented below code for multiprocessing that can handle multiple request concurrently but I'm getting below error. For that i use producer and consumer concept where producing putting process in queue and consumer consume that process and do some JOB. Traceback (most recent call last): p.start() File "/usr/lib/python2.7/multiprocessing/process.py", line 130, in start self._popen = Popen(self) File "/usr/lib/python2.7/multiprocessing/forking.py", line 121, in __init__ self.pid = os.fork() OSError: [Errno 12] Cannot allocate memory queue = Queue() lock = Lock() producers = [] consumers = [] for frame in frames: `enter code here`producers.extend([Process(target=self.producer, args=(queue, lock, frame)) for i in xrange(cpu_count())]) for i in range(50): p = Process(target=self.consumer, args=(queue, lock)) p.daemon = True consumers.append(p) for p in producers: #time.sleep(random.randint(0, 5)) p.start() for c in consumers: #time.sleep(random.randint(0, 5)) c.start() # Like threading, we have a join() method that synchronizes our program for p in producers: p.join() u_end = time.time() print u_start, u_end print('Parent process exiting...')