Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JQuery: div class-specific hover not working with bootstrap css
Context: Developing a "google-calendar-like" hardware booking tool at work using DJango. View reservations (their time slot and reserving user). Click empty space to create another reservation (bootstrap modal form) Click on your own reservation to edit (bootstrap modal form) "Calendar" is updated dynamically by querying server (AJAX - GET). Reservation data is updated in a similar fashion (AJAX - POST). example The "calendar" is a custom setup made entirely of divs (I was having trouble with positioning of reservations inside td). <main class="container"> <div class="calendar"> <div class="calendar_col"> <div class="calendar_header"></div> {% for time in time_range %} <div class="calendar_header">{{ time }}:00 - {{ time|add:1 }}:00</div> {% endfor %} </div> {% for weekday in weekdays %} <div style="height: {{ time_range|length|add:1|mul:1.25 }}em" class="calendar_col" id="{{ weekday|lower }}"> <div class="calendar_header">{{ weekday }}</div> {% for time in time_range %} <div id='{{ weekday|lower }}_{{ time }}h' class="calendar_seperator" style="position: absolute; top: {{ forloop.counter|mul:1.25 }}em">&nbsp;</div> {% endfor %} </div> {% endfor %} </div> </main> Some reservations can span multiple days (such as Monday to Thursday in example image). To make it easier to identify such, I want to highlight all the concerned blocks when hovering with mouse. When creating the blocks I give the the "reservation" class and "weekday_reservationpk" for … -
request.POST not found
Got a confusing error. I have this view that, when hit with a post request, should simply print the contents of the request.POST dict to the terminal. However, it says that it doesn't have an attribute 'post'. How is this possible if we're in the post method? class AddWorkoutView(View): def get(self, request, year=None, month=None, day=None): template_name = 'workoutcal/addworkout.html' template = loader.get_template(template_name) date = datetime(year=int(year), month=int(month), day=int(day)) context = { 'date':date, 'current_name':request.user.username, 'title':'Add workout', 'range':range(4), } return HttpResponse(template.render(context, request)) def post(self, request, year=None, month=None, day=None): print(request.POST) # ERROR HERE return HttpResponse("Sent workout. Find in terminal") urls.py: url(r'^add/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/$', views.AddWorkoutView.as_view(), name = 'add_workout'), The error: Internal Server Error: /workoutcal/add/2017/11/22/ Traceback (most recent call last): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/workoutcal/views.py", line 100, in post print(request.POST) AttributeError: 'WSGIRequest' object has no attribute 'post' EDIT: In case you want to see the form sending the POST request: <form action="{% url 'workoutcal:add_workout' date.year date.month date.day %}" method="post"> {% csrf_token %} … -
Serving static files in production with Apache and FastCGI
I am trying to put my django website to production, but I have a problem with static files. There are plenty of questions about this on google, but none of them helped me. I use Django 1.8.7 with FastCGI and Apache. Everything runs just fine, except of my css. It is not working in templates. I did python manage.py collectstatic and all my static files got copied to /home/username/public_html/mysite/static I also did urlpatterns += staticfiles_urlpatterns() in mysite.urls My settings are: BASE_DIR = '/home/username/public_html/mysite/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' In my template I use {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> It gives <link rel="stylesheet" type="text/css" href="/static/style.css"> in template when I check generated html in browser (I think that's ok, isn't it?), but no css works. Do you have a clue, what could help? Do I have to set something for Apache to serve static files? Thanks for your answers. -
Coverage report explanation
I am using pytest-cov to obtain coverage report for a django project (containing folders 'src' for source files and 'tests' contains the tests) using command: pytest --cov-report term --cov=src tests One of the source files, say B, uses a decorator which is defined in file A. The decorator takes in two functions as its parameter which are initialized in file A: def decorator_func(func1=play, func2=stop): ... In file B, 'decorator_func' is used with parameter func2=pause where pause() is defined in file B. In the coverage report for file B, the lines of 'pause' function are shown as missed, but those lines are executed. This affects the percentage coverage. I am trying to understand why this happens? Is it because the decorator function is defined in another file i.e file A? -
Django website not checking the links correctly
I have a django website that contains a table with many servers details. In one of the columns in the table there is "ILO" IP of a server. I wanted the website to check if the "ILO" IP works in http request, and if it does, then it should show the link and if not, shows a text instead. Therefore, in the result, will be servers that has http link to ILO IP and some without. Under my main class in the views I created a function called "checkUrlAvailable" which I try to use in my index.html and check with if condition if I get true or false.. for some reason I get the errorr- Could not parse the remainder: '(server.IP)' from 'checkUrlAvailable(server.IP)' Does anyone know why? index.html- <tr> <th><center> #</center></th> <th width="100%"><center> Server Name </center></th> <th><center> Owner </center></th> <th><center> Project </center></th> <th width="100%"><center> Description </center></th> <th width="100%"><center> IP Address </center></th> <th width="100%"><center> ILO </center></th> <th><center> Rack </center></th> <th><center> Status </center></th> <th><center> Actions {{ response }} </center></th> </tr> </thead> <tbody> {% for server in posts %} <tr> <div class ="server"> <td></td> <td style='white-space: nowrap'><center>{{ server.ServerName }}</center></td> <td width="100%"><center>{{ server.Owner }}</center></td> <td style='white-space: nowrap'><center>{{ server.Project }}</center></td> <td style='white-space: nowrap'><center>{{ server.Description }}</center></td> … -
extending default User model in Django
I've written my first application Django 2.0. Everything is working fine and the application is almost ready when I realized to replace id primary key field from default integer type to UUID to make database entry more secure. When I searched for this how to change id of user table to UUID I got many tutorials extending AbstractBaseUser. Here is I have written own User model. account/models.py class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) But I'm confused more with examples on different sources. Every example is adding few more fields in extended model like first_name last_name is_staff is_admin active and functions as def get_fullname(self): def get_shortname(self): etc. I think all these fields and functions are there by default in AUTH_USER_MODEL. Does extending AbstractBaseUser overwrites AUTH_USER_MODEL and it is required to add all fields which is there by default? also, I'm using settings.AUTH_USER_MODEL as foreign key in different models. Should It be replaced by account.User model? I'm also using django-allauth plugin to enable login using the social network and use email only for authentication. Do I require to add email field in the extended model with unique=True? -
where to find "if logic" module, python?
I needed to pass a variable in the "if" logic module if it's possible, so I won't need to recreate it? What I want to achieve; Class PythonIfModule(statement): # Code Logic Return Something statement = '(True And True) And "(False And True)' result = PythonIfModule(statement) If you must know what it's for, I need it in the Certainty Factor's conjunction and disjunction of hypothesis; since the system only accepts an Evidence with a certainty factor of 1.0 (True) and 0.0 (False). -
Reverse relationships for accessing user's profile
In my app, there are users with 0 or 1 profile at the same time. Over the time, I project to have many different profiles. Accessing user from profileX is easy : profile_x_object.user But what about the reverse relation? I'd like to find the best generic way to create a relation from user to its profile. For now, I created a property named profile to fill that purpose. It works but it need to be updated foreach new profile I add over time. Any idea to do better? Here is the code I have: class User: # ... @property def profile(self): if hasattr(self, 'profilea'): return self.profilea if hasattr(self, 'probileb'): return self.probileb class BaseProfile(models.Model): class Meta: abstract = True user = models.OneToOneField(settings.AUTH_USER_MODEL) class ProfileA(BaseProfile, models.Model): # ... class ProfileB(BaseProfile, models.Model): # ... -
how to sorted some shops by distance in django
I have latitude and longitude and I want to pull the record from the database mongodb, i want select all table sorted by distance model: class Location(DynamicDocument): type = fields.StringField() coordinates = fields.ListField(FloatField()) class Products(Document): picture = fields.StringField() name = fields.StringField() email = fields.StringField() city = fields.StringField() location = fields.EmbeddedDocumentField('Location') -
Django '/' only homepage url error
I am using Django 2.0 and now I have no idea how to make an 'empty' url for the homepage. Meaning, I want it to route for web.com/ or web.com. I tried this code but it does not work: urlpatterns = [ path('admin/', admin.site.urls), path('/', include('post.urls')) ] ...and post.urls urlpatterns = [ path('', views.index, name='index') ] And the error I get when I make a request to localhost:8000: Request URL: http://localhost:8000/ Using the URLconf defined in myblog.urls, Django tried these URL patterns, in this order: admin/ / The empty path didn't match any of these. I did sort of find a workaround by setting path to an empty string '' on both but I am not sure if it is recommended or what errors it might cause. Help is much appreciated. Thank you :-). -
how to render output from django view to angularjs app
I have a django view which is called using a angular frontend controller and an image is passed to it,and some processing is done on it and output is generated.now i want to render this output to angularjs app instead of giving it to my template.In other words i dont want to use any templates for rendering this output to user, but do it using angular. app.js $scope.segmentImage = function(image) { $http({method:'POST', url:'http://127.0.0.1:8000/image/script_function/', data:{'image': image}}) .then(function successCallback(response) { console.log('Image Posted successfully') },function errorCallback(response) { console.log('Image Post failed') } )}; views.py from django.shortcuts import render def segment_image(request): if request.method == 'GET': form = segment_form() else: if form.is_valid(): info = request.POST['info_name'] output = script_function(info) ''' Here i am calling script_function,passing the POST data info to it''' return render(request, 'your_app/your_template.html', { 'output': output, }) return render(request, 'your_app/your_template.html', { 'form': form, }) '''here info is our image in some format''' def script_function(info): '''here goes my main logic''' x=y=w=h=102 return x,y,w,h -
How to automate Django-App_EXE created by using pyinstaller and innosetup
I have created an EXE file for my django application. After creating EXE each and everytime i need to run EXE by command line for example : mysite.exe runserver To be more detailed : OS: windows(CMD), Used pyinstaller to pack all deppendency softwares and later innosetup to make installer. I have tried to create a batch file to automate the EXE run as given below: SET PATH=%PATH%;C:\Program Files (x86)\cook_cake\; start http://localhost:8000 & C:\"Program Files (x86)"\cook_cake\cookie_cake.exe runserver This batch script is not producing desired result.Even this batch script has to run in background when i click on application. My assumption is error is there in batch script. -
Django: Image Compression
I'm trying to compress Image before Uploading it to the database. Here's what I tried, from PIL import Image as Img from PIL import Image try: from StringIO import StringIO except ImportError: from io import StringIO class Profile(models.Model): profile = models.ImageField(upload_to='user_image', blank=True) def save(self, *args, **kwargs): if self.profile: img = Img.open(StringIO.StringIO(self.profile.read())) if img.mode != 'RGB': img = img.convert('RGB') img.thumbnail((self.profile.width / 1.5, self.profile.height / 1.5), Img.ANTIALIAS) output = StringIO.StringIO() img.save(output, format='JPEG', quality=70) output.seek(0) self.profile = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.profile.name.split('.')[0], 'image/jpeg', output.len, None) super(Profile, self).save(*args, **kwargs) Problem is, whenever I try to upload an image it's raising an error, img = Img.open(StringIO.StringIO(self.profile.read())) type object '_io.StringIO' has no attribute 'StringIO' How can we fix that? Thank You very much . . . -
django 2.0 url.py include namespace="xyz"
I've a problem with the routing django.conf.urls include() - main project folder - urls.py Line 22 of urls.py (pip freeze and urls.py - see below) throws the error in the console: Quit the server with CONTROL-C. [02/Jan/2018 14:22:49] "GET /api/compositions/ HTTP/1.1" 200 30058 [02/Jan/2018 14:22:53] "GET /api/compositions/1/ HTTP/1.1" 200 6195 Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f17ee06e400> Traceback (most recent call last): File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/urls/resolvers.py", line 397, in check for pattern in self.url_patterns: File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/ernst/django_virtualenv/lib/python3.4/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/ernst/django_virtualenv/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen … -
ListView and a form in single page
I have a blog.html which I will list all blog posts in my model using a generic class-based view ListView and it will point to www.example.com/blog. I also want to add a form not by pointing to a new page/url but all the list of blog posts plus that form. This post has a similar situation like me and the answer says add the form to TEMPLATE_CONTEXT_PROCESSORS. So after doing this, how can I use the form in my blog.html? -
Django refering to same model instances in Abstract Model
I have an abstract model from which a couple of my main models are inherited. Main difficulty in this case is that I have a need in reference to the same model, like a ForeignKey to self. I have read that the ForeignKey is not possible in abstract models and GenericForeignKey can help, however I can`t really make it work. As I understand structure should be somethig like following: class BaseModel(models.Model): versions = GenericRelation('self') date_created = models.DateTimeField(default=datetime.datetime.now) is_deleted = models.BooleanField(default=False) content_type = models.ForeignKey(ContentType, blank=True, null=True) object_id = models.PositiveIntegerField(blank=True, null=True) content_object = GenericForeignKey('content_type', 'object_id') class FirstModel(BaseModel): some_fields... class AnotherModel(BaseModel): another_fields... But with this approach I get an error: >>> item1 = FirstModel.objects.get(id=1) >>> item2 = FirstModel.objects.get(id=2) >>> item2.content_object = item1 Traceback (most recent call last): File "<input>", line 1, in <module> File "/home/michael/.virtualenvs/diagspecgen/lib/python3.6/site-packages/django/contrib/contenttypes/fields.py", line 245, in __set__ ct = self.get_content_type(obj=value) File "/home/michael/.virtualenvs/diagspecgen/lib/python3.6/site-packages/django/contrib/contenttypes/fields.py", line 163, in get_content_type return ContentType.objects.db_manager(obj._state.db).get_for_model( AttributeError: 'ReverseGenericRelatedObjectsDescriptor' object has no attribute '_state' Is that I am trying to reach is absolutly impossible and the only solution is to explicitly create needed fields in existing models? Thanks in advanse for your suggestions. -
AttributeError: model object has no attribute 'rel'
In django 1.9 I used this custom MultilingualCharField, then I upgrade to django 2.0 and it give error: class MultilingualCharField(models.CharField): def __init__(self, verbose_name=None, **kwargs): self._blank = kwargs.get("blank", False) self._editable = kwargs.get("editable", True) #super(MultilingualCharField, self).__init__(verbose_name, **kwargs) super().__init__(verbose_name, **kwargs) def contribute_to_class(self, cls, name, virtual_only=False): # generate language specific fields dynamically if not cls._meta.abstract: for lang_code, lang_name in settings.LANGUAGES: if lang_code == settings.LANGUAGE_CODE: _blank = self._blank else: _blank = True localized_field = models.CharField(string_concat( self.verbose_name, " (%s)" % lang_code), name=self.name, primary_key=self.primary_key, max_length=self.max_length, unique=self.unique, blank=_blank, null=False, # we ignore the null argument! db_index=self.db_index, rel=self.rel, default=self.default or "", editable=self._editable, serialize=self.serialize, choices=self.choices, help_text=self.help_text, db_column=None, db_tablespace=self.db_tablespace ) localized_field.contribute_to_class(cls, "%s_%s" % (name, lang_code),) def translated_value(self): language = get_language() val = self.__dict__["%s_%s" % (name, language)] if not val: val = self.__dict__["%s_%s" % (name, settings.LANGUAGE_CODE)] return val setattr(cls, name, property(translated_value)) def name(self): name_translated='name'+settings.LANGUAGE_CODE return name_translated Here's the error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03BCB8E8> Traceback (most recent call last): File "D:\Python\Envs\possedimenti\lib\site-packages\django\utils\autoreload.py ", line 225, in wrapper fn(*args, **kwargs) File "D:\Python\Envs\possedimenti\lib\site-packages\django\core\management\com mands\runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "D:\Python\Envs\possedimenti\lib\site-packages\django\utils\autoreload.py ", line 248, in raise_last_exception raise _exception[1] File "D:\Python\Envs\possedimenti\lib\site-packages\django\core\management\__i nit__.py", line 327, in execute autoreload.check_errors(django.setup)() File "D:\Python\Envs\possedimenti\lib\site-packages\django\utils\autoreload.py ", line 225, in wrapper fn(*args, **kwargs) File "D:\Python\Envs\possedimenti\lib\site-packages\django\__init__.py", line 24, in … -
Django - Why PATCH returns in response correct data which I would like to save but it doesn't save this data in database?
Any ideas why PATCH returns in response correct data which I would like to save but it doesn't save this data in database? def patch(self, request, portfolio_id): try: object = Object.objects.get(id=object_id) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = ObjectSerializer(object, data=request.data, partial=True) if serializer.is_valid(): serializer.save(object=object) return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django display an image while rendering request
I want a simple loading screen to be displayed while my django function is done. I read that Ajax might be able to do this, but non of the explanations are clear. So basically i have a small index view: def index(request): return render(request, 'index.html', {'form': forms.AnalysisType()}) This index page has a Submit button, and when it is pressed a plot view is rendered. The plot view takes some time to load, an i would like to display a loading GIF in my page while it loads. The plot view is long and complicated, but in the end it should return a render(request) call. I tried adding something like this to my index.html template, but it did not work: <script> $(document).ready(function () { //Attach the ajaxStart and ajaxComplete event to the div $('#prgs').ajaxStart(function() { $(this).show(); }); $('#prgs').ajaxComplete(function() { $(this).hide(); }); //Perform the AJAX get $.get('/plot/', function(data) { //Do whatever you want with the data here }); }); </script> -
Passing context to django-registration's views
I'm utilizing django-registration with a set of premade templates I found on Github for doing a two-step (registration-activation) workflow using HMAC. I want to pass variables like my website's name to the emails sent by django-registration. the activation email sent to a new registrant, for example, or the password change one. The "problem" is I don't directly have access to those views. That's kinda the point of django-registration, you include its path in the urls.py file, and everything works: urlpatterns = [ url(r'^', include('core.urls')), url(r'^admin/', admin.site.urls), url(r'^accounts/', include('registration.backends.hmac.urls')), ] What's the minimum effort way of adding context to those views? I've already created and am successfully passing context to emails in my own views (using context processors): def send_some_email_view(request): msg_plain = render_to_string('email_change_email.txt', context, request=request) msg_html = render_to_string('email_change_email.html', context, request=request) But what about views I didn't create? -
django tesy using selenium package error
7 and want to create some django test using selenium package. here the simple test : import unittest from selenium import webdriver class TestSignup(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() def test_signup_fire(self): self.driver.get("http://localhost:8000/add/") self.driver.find_element_by_id('id_title').send_keys("test title") self.driver.find_element_by_id('id_body').send_keys("test body") self.driver.find_element_by_id('submit').click() self.assertIn("http://localhost:8000/", self.driver.current_url) def tearDown(self): self.driver.quit if __name__ == '__main__': unittest.main() but I take this error : TypeError: environment can only contain strings in this line : self.driver = webdriver.Firefox() and I don't know why,any idea how to can fix this error ? -
How to get average of 6 first elements in a queryset and annotate the value in Django?
I have 2 models that are something like this: class Foo(models.Model): name = models.CharField(max_length=30) class FooStatement(models.Model): foo = models.ForeignKey(Foo, on_delete.models.CASCADE) revenue = models.DecimalField(decimal_places=2) date = models.DateField() What I want to know is what the average is of the FooStatement revenue for the first 6 dates for each Foo object. Is there any way to achieve this? I was thinking of slicing the first 6 entries (after ordering them), but I cannot seem to get this to work. The statement months all start at different dates so I can't just say that I want all dates that are lesser than 'x'. I'm almost positive the answer lies somewhere in clever annotation, but I just cannot find it. -
Image Compression Before Upload
I'm trying to compress Image before Uploading it to the database. Here's what I tried, from PIL import Image as Img from PIL import Image try: from StringIO import StringIO except ImportError: from io import StringIO class Profile(models.Model): profile = models.ImageField(upload_to='user_image', blank=True) def save(self, *args, **kwargs): if self.profile: img = Img.open(StringIO.StringIO(self.profile.read())) if img.mode != 'RGB': img = img.convert('RGB') img.thumbnail((self.profile.width / 1.5, self.profile.height / 1.5), Img.ANTIALIAS) output = StringIO.StringIO() img.save(output, format='JPEG', quality=70) output.seek(0) self.profile = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.profile.name.split('.')[0], 'image/jpeg', output.len, None) super(Profile, self).save(*args, **kwargs) Whenever I try to upload a image it's raising an error type object '_io.StringIO' has no attribute 'StringIO' How can we fix that? Thank You . . . -
how to read excel data and insert into msql database dynamically using pandas in python 3.X
I have been able to get the headers and able to create table but can't get the excel content and insert excel content by lines each into the database columns import pandas as pd import sqlalchemy as sa import pymysql from pymysql import DatabaseError class ReadCSV(): def read(self, path): clean_header = '' #db = pymysql.connect("localhost", "root", "password", "test") try: df = pd.read_csv(path, skiprows=1, na_values=['not available','n.a.','']) unclean_headers = df.columns for header in unclean_headers: #header = self.clean_data(header) clean_header +=self.header_cleanup(header) #remove the last commas clean_header = clean_header[:-1] #create new table and columns #self.create_tab(clean_header) # insert the csv content in db datas = pd.read_csv(path, chunksize=100000, skiprows=2,header=None, na_values=['not available','n.a.',' ']) for data in datas.split('\n'): #======= I need to get each columns and insert the into data base print(data) except ValueError: print('Invalid value') except: print('Error') thanks in advance -
Issue with importing rest_framework inside django app
I am facing an issue of importing rest_framework inside my django app whenever i try to make migrations or create superuser or simply run the runserver. I have installed the framework using this command but django still doesn't recognize it sudo pip install djangorestframework here's the snippet of settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'companies.apps.CompaniesConfig', ] REST_FRAMEWORK = { 'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.HyperlinkedModelSerializer', # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] }