Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django JSONField Filtering with Complex JSON
I have the following model: class Websites(models.Model): website_name = models.CharField(max_length=255,null=False) website_json_data = JSONField(blank=True,null=True,default=dict) def __str__(self): return self.website_name json_data contains 2 keys : headers[LIST] and body[DICT] in following with lot of json objects json_data = {"api.google.com": {"headers": ["Accept-User", "Mozilla","etc"], "body": "<html><title>sagsdgsdgsdgsdg</body>"},"api.facebook.com":{"headers":["Content-Type","User-Agent"],"body":"<html><title>this is facebook</title>"} p = Websites.objects.create(website_name="google.com",website_json_data=json_data) p.save() How do I filter the results in such a case? Q1) How do I filter the results based on body contains in such case? EX: I would like to return the results if any of the json object body contains this is facebook -
DRF Foreignkey serialization
I can't save model with Foreignkey field. For example I have simple models: class User(AbstractUser): class Meta: pass email_validator = EmailValidator() username = models.CharField('Name', max_length=150, ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField('Email', blank=True, unique=True, validators=[email_validator], ) ... class Package(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='packages') description = models.CharField('Description', max_length=256, default='description') weight = models.CharField('weight', max_length=256, default='weight') ... View (the user is guaranteed to be in the request): @api_view(["POST"]) def test(request): data = request.data data['user'] = User.objects.get(id=request.user.id) serializer = PackageSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) else: return JsonResponse(serializer.errors) My serializers: class UserSerializer(ModelSerializer): class Meta: model = User fields = '__all__' class PackageSerializer(ModelSerializer): class Meta: model = Package fields = ( 'user', 'description', 'weight', 'dimensions', 'estimated_shipping_cost', 'deliver_to_date') def to_representation(self, instance): self.fields['user'] = UserSerializer(many=False, read_only=True) self.fields['where_from'] = LocationSerializer(many=False, read_only=True) self.fields['destination'] = LocationSerializer(many=False, read_only=True) return super().to_representation(instance) def create(self, validated_data): user = User.objects.get(validated_data.pop('user')) package = Package.objects.create(user=user, **validated_data) return package json in request: { "description": "Some package", "weight": "12", } So, I'have user in database, and want create package for him. But in overridden create in PackageSerializer, validated_data doesn't have user. Please explain what I'm doing wrong. Versions of django and drf: django==2.2.4 djangorestframework==3.10.2 -
Why dou you have this error: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied
i cant work with django when its coming sometimes is coming some times not. -
how to upload image in django CBV(class based Views)createviews
I have been working on creating a blog sharing application using django.Am trying to add an image field so that users will be able to upload images and view them as posts.But the image is not getting uploaded.Django is not even throwing any errors. The code is running fine but the image is not getting uploaded. i have tried adding "enctype" in the template,as well as making the necessary changes in urls.py. I have even specified the MEDIA_ROOT and MEDIA_URL in settings.py. if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have added this in my urls.py. My models.py from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='% (app_label)s_%(class)s_related') picture = models.ImageField(upload_to='images',default='default.png',null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('project-home') My Views.py class PostCreateView(SuccessMessageMixin,LoginRequiredMixin,CreateView): model = Post fields = ['title','content','picture'] success_message = 'Your submission is sucessful!' def form_valid(self,form): form.instance.author = self.request.user return super().form_valid(form) def get_success_message(self): return self.success_message the image is not getting uploaded.Thanks in advance! -
Calling second GET request for separate view in Django
I am trying to call the GET method in my show_page view when the GET method in the main_page view is called. With the code I am using now, I know the show_page GET method is being called because I tested it with a print statement. However, it is not creating the actual GET request so that the page refreshes. Thank you for any help you can provide! class show_page(LoginRequiredMixin, View): template = 'wait/show.html' @classmethod def get(cls, request): username = request.user.username customers = Customer.objects.filter(store_username=username).exclude(exited=True) return render(request, cls.template, {'customers' : customers}) class main_page(LoginRequiredMixin, View): template = 'wait/main.html' def get(self, request): username = request.user.username customers = Customer.objects.filter(store_username=username).exclude(exited=True) refresh = show_page.get(request) return render(request, self.template, {'customers' : customers}) -
Django - Saving object worked one time but now it doesnt
i want to save an object to db and it worked one time but now it doesnt, i suspect that is something to do with the Glossary Everything views.py @login_required def product_form_view(request): if request.method == 'POST': form = Product_Form(request.POST, request.FILES) if form.is_valid(): product_form = form.save() product_form.save() return redirect('product_management_view') else: form = Product_Form() return render(request, 'product-form.html', {'form': form}) models.py class Product (models.Model): sub_chapter = models.ForeignKey(Sub_Chapter, on_delete=models.CASCADE) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) glossary = models.ManyToManyField(Glossary, blank=True ) name = models.CharField(max_length=40, blank=False, null=False) description = models.TextField(null=True) product_image = models.ImageField( upload_to='media/images/product_images', blank=False, null=False) reference = models.CharField(max_length=40, blank=False, null=False) width = models.PositiveIntegerField() height = models.PositiveIntegerField() length = models.PositiveIntegerField() unit_price = models.DecimalField( max_digits=15, decimal_places=4, null=True) polution = models.DecimalField(decimal_places=8, max_digits=15, null=True, blank=True ) technical_implementation = models.TextField(null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse_lazy("manufacter_product_view", kwargs={'id': self.pk}) forms.py class Product_Form(forms.ModelForm): sub_chapter = forms.ModelChoiceField(queryset=Sub_Chapter.objects.all(), required=True, widget=forms.Select()) supplier = forms.ModelChoiceField(queryset=Supplier.objects.all(), required=True, widget=forms.Select()) glossary = forms.ModelChoiceField(queryset=Glossary.objects.all(), required=False, widget=forms.SelectMultiple()) product_image = forms.ImageField( required=True, widget=forms.FileInput()) class Meta(): model = Product fields =[ 'name', 'description', 'reference', 'width', 'height', 'length', 'polution', 'unit_price', 'technical_implementation', 'sub_chapter', 'supplier', 'glossary', 'product_image', ] -
Django: Delete or empty content of a row in UpdateView
I'm looking to delete or empty a specific row in my table/model in my UpdateView. I have a team and employees in the team. I have made an update view that when "yes" is pressed, the team becomes archived. I want to additionally delete or empty the employee's numbers when doing so. How would I approach that? I know it might be weird, but the idea is that the employee's numbers should be destroyed once the team is archived, while the rest of the data still stands. Team Model class Team(models.Model): slug = models.SlugField(max_length=200) teamname = models.CharField(max_length=50, help_text="Indtast holdnavn.", null=False, primary_key=True) is_active = models.BooleanField(default=True) Employee Model class Employee(models.Model): id = models.AutoField(primary_key=True) slug = models.SlugField(max_length=200) emp_num = models.IntegerField(help_text="Indtast medarbejderens MA-nummer. (F.eks 123456)") firstname = models.CharField(max_length=30, help_text="Indtast medarbejderens fornavn.") lastname = models.CharField(max_length=30, help_text="Indtast medarbejderens efternavn.") teamname = models.ForeignKey('Hold', on_delete=models.CASCADE, null=True) UpdateView My updateView is using team, as its that model I'm updating. class ArchiveHoldView(UpdateView): template_name = 'evalsys/medarbejder/archive_hold.html' model = Team form_class = ArchiveForm def archive_view_team_with_pk(self, slug=None): if slug: team = Team.objects.get(slug=slug) else: team = self.team args = {'team': team} return render(self, 'evalsys/medarbejder/archive_hold.html', args) def get_context_data(self, **kwargs): context = super(ArchiveHoldView, self).get_context_data(**kwargs) context['is_active'] = Team.objects.get(slug=self.kwargs.get('slug')) return context def get_success_url(self): return reverse_lazy("evalsys:home") -
DRF - multiple user model and authentication
Let say I need to have this users: - user model from imported package (it is for customer to login, it using SSO from other project), it has their own authentication too. - own user model that different from imported package (it is only for admin to access backend and DRF API for this project) how to implement that? I only know that i have to change 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', 'imported_user_package', ... ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'imported_user_package.authentication.SSOAuthentication', ), ... } AUTH_USER_MODEL = 'imported_user_package.UserModel' how to create own user model, and use it for access admin backend and API with default rest framework authentication ? -
Django-Rest-Framework- How to make model serializer extra fields respect the depth
I would like to understand/control the depth argument of nested serializers. For some fields it works, for some others it does not. The serializer: class MyUserSerializer(serializers.ModelSerializer): cars = CarSerializer(read_only=True, many=True) class Meta: model = MyUser fields = '__all__' depth = X with depth=0 in the serializer class: { 'name': 'foo', 'cars': [<list of car ids>] } with depth=1: { 'name': 'foo', 'cars': [<list of car objects>] } If the list of cars is a ManyToManyField or a ForeignKey, everything works. If the list of cars is a User Model method, then the depth has no impact. What I mean by User Model method (just an example from models.py): class User(models.Model): ... def cars(self): return models.Car.objects.all() What would you recommend ? My final goal is to dynamically change the depth using query params such as in Django Rest Framework : Nested Serializer Dynamic Model Fields -
Capture print statements and yield them to StreamingHttpResponse
I'm writing a module that prints its progress as it loads data, does some calculations, and saves the result, roughly like this: def process_data(): print('Loading data...') data = load_data() print('Data loaded. Starting calculations...') result = calculate(data) print('Calculations complete. Saving result...') save_result(result) print('Done.') I want to connect this module with a Django view so that the end user can see the progress of the print statements as it runs. This appears to be possible using StreamingHttpResponse, which accepts an iterator and sends any yielded text to the browser as it runs. So far I had some success by changing print to yield in the main function. But when I tried to change print to yield in the calculate function, it got rather messy: from django.http import StreamingHttpResponse def process_data_view(request): return StreamingHttpResponse(process_data()) def process_data(): yield '<pre>Loading data...\n' data = load_data() yield 'Data loaded. Starting calculations...\n' # Here's where it got messy: for printline_or_result in calculate(data): # when calculate function yields a string, take it as a line to print if isinstance(printline_or_result, str): yield printline_or_result # when calculate function yields a non-string, take it as the result else: result = printline_or_result yield 'Calculations complete. Saving result...\n' save_result(result) yield 'Done.\n' Is there any better … -
Celery Periodic Tasks check for database changes
I'm trying to implement Fetcher app. I have DB where I store url and interval(seconds) and django celery beat for periodic tasks to fetch these urls after X seconds periodically. Is it possible to handle database updates(POST's and DELETE's) on my DB while my celery beat and workers are running? Could you give me an example how to achieve that? Example of my problem: 4 tasks, ids: [1,2,3,4] turning on celery beat and worker everything works great till we delete, for example id 2 celery still trying to run periodic task for 4 tasks instead of 3. @app.on_after_finalize.connect def setup_periodic_tasks(sender, **kwargs): logging.info('[*] Setting up periodic tasks...') from api.models import RequestModel queryset = RequestModel.objects.all() for req in queryset: sender.add_periodic_task(req.interval, fetch_url.s(req.id, req.url)) -
Is there any way to get current user from the request? I am getting annonymous user even though user is loggedin
This is my first app in django + react so I am not professional. I am writing viewset and trying to get current user from the request but I got anonymous user even though user is loggedin. My frontend is in react and I am using allauth and rest-auth for django authentication. Please help! I was trying to find out if there is an issue with token but it seems that works fine that. I have also CustomUser so maybe is that... Here is my login func in react redux: export const authLogin = (username, password) => { return dispatch => { dispatch(authStart()); axios.post('http://127.0.0.1:8000/rest-auth/login/', { username: username, password: password }) .then(res => { console.log("RESPONSE LOGIN") console.log(res) const token = res.data.key; const user = username; const expirationDate = new Date(new Date().getTime() + 3600 * 1000); localStorage.setItem('token', token); localStorage.setItem('user', user); localStorage.setItem('expirationDate', expirationDate); dispatch(authSuccess(token)); dispatch(checkAuthTimeout(3600)); }) .catch(err => { dispatch(authFail(err)) }) } } const authSuccess = (state, action) => { return updateObject(state, { token: action.token, error: null, loading: false }); } and here is my viewset and custom user model: class MatchViewset(viewsets.ViewSetMixin, generics.ListAPIView): serializer_class = MatchSerializer def get_queryset(self): user = self.request.user print(user) return Match.objects.filter(creator=user) class CustomUser(AbstractUser): GENDER_CHOICES = ( ("F", "FAMALE"), ("M", "MALE") … -
Why can't django's reverse() match an email parameter?
I'm using a DRF ViewSet to manage user accounts: class UserViewSet(ModelViewSet): lookup_field = 'email' queryset = User.objects.all() And have a testcase like: from django.urls import reverse from .base import BaseApiTestCase class UsersTestCase(BaseApiTestCase): def test_get_user_account(self): # ...Create a test user, login as test user... response = self.client.get( reverse('api:users-detail', kwargs={'email': 'test@user.com'}), content_type='application/json' ) self.assertStatusCode(response, 200) I get the error: django.urls.exceptions.NoReverseMatch: Reverse for 'users-detail' with keyword arguments '{'email': 'test@user.com'}' not found. 2 pattern(s) tried: ['api/users/(?P<email>[^/.]+)\\.(?P<format>[a-z0-9]+)/?$', 'api/users/(?P<email>[^/.]+)/$'] It's my understanding that the [^/.]+ regex should match test@user.com. Although reverse() should do this for me, I've also tried url-encoding the @ symbol, as in: reverse('api:users-account', kwargs={'email': 'test%40user.com'}), Running manage.py show_urls reveals that the URL is available: ... /api/users/<email>/ api.views.users.UserViewSet api:users-detail ... Why can't django's reverse() system find the url match? -
Django - Accessing Foreign Key values to save to dictionary
In Django, I would like to create a dictionary from model values which also include the Foreign Key values. So, for example, I have 2 models: --models.py-- class Item(models.Model): item_name = models.CharField(max_length=255) item_description = models.CharField(max_length=255) class Inventory(models.Model): inventory_name = models.CharField(max_length=255) inventory_date = models.DateTimeField(default=timezone.now) inventory_item = models.ForeignKey(Item, on_delete=models.DO_NOTHING) (not the best variable name examples since it could be a many to many relationship, but you get the point) In my urls, I need a path that shows the primary key because I will have some other functions based their pks from the URL. --urls.py-- urlpatterns = [ path('details/ < int : pk > /', views.GenerateDetails, name='details'), ] Now, here's were I'm having issues. I'm trying to create a dictionary from the Inventory model that will also have the ForeignKey values from Item. --views.py-- class GenerateDetails(View): def get(self, request, *args, **kwargs): inventory_data = Inventory.objects.get(pk=self.kwargs.get('pk')) # Create dictionary from selected contract_data inventory_data_dict = model_to_dict(inventory_data) ... return response From this solution, the only ForeingKey value that the dictionary saves is Item__id and that's it. I would like the dictionary to save all the data for Inventory as well as Item__name and Item__description. -
Error with Django Postgis DB as default backend
I am new to development generally and django. Currently I have the error below when I use the 'python manage.py runserver' command after changing Default Database Engine on setting to "'ENGINE': 'django.contrib.gis.db.backends.postgis'" cannot import name 'GDALRaster' from 'django.contrib.gis.gdal' What can I do. Please find picture below; error message -
Counting model field dynamically?
Is it possible to count a model field dynamically in django. I have tried using override save model but this is not dynamic: class MyAdminView(admin.ModelAdmin): def save_model(self, request, obj, form, change): super(MyAdminView, self).save_model(request, obj, form, change) Models.py class ClientProfile(models.Model): name=models.CharField(max_length=200) organization=models.CharField(max_length =150) email=models.EmailField(max_length =150) country= models.CharField(max_length =150) state=models.CharField(max_length =150) publish=models.BooleanField(default =True) active = models.CharField(max_length =150) present=models.CharField(max_length =150) I want to the present field to count the number of times a name(specific) to a user is mention and the active to count the publish field related to a user with name(specific) -
i just wanted to pass seperate fields to template via render, i tried deserializing but it didnt work, help will be really appreciated
here is my get function im sending whole serialized object to template which not letting me use fields seperately in template @api_view(['GET']) def get_employee(request): emp = employee.objects.all() serializer = employeeSerializer(emp, many=True) return render(request,'employee/employee_details.html',{'json_obj': serializer.data}) -
Need help to solve complex sql query with django queryset
I need help to translate a sql query to a django queryset... I have tried many things but nothing that can solve it The query below is exactly what I need and it actually give me the result I expect. Can anyone help me on this case ? SELECT DISTINCT on (name) * FROM my_table WHERE (name, job_result_id) = ANY( SELECT name, max(job_result_id) FROM my_table WHERE ticket != '' GROUP BY name, job_result_id) Thanks for your help -
Django rest framework: sendgird email with attachment without model only filefield to open file and send button to send email
I am new on Stackoverflow. Don't know how to ask question. I am new on Django Rest Framework Also. I am trying to send email with attachment. Here is my code. *****model.py******* class EmailModel(models.Model): upload_file = models.FileField(upload_to='location/location/files', blank=False) class Meta: verbose_name = 'Applicant CSV Upload' verbose_name_plural = 'Applicant CSV Upload' *****admin.py***** @admin.register(EmailModel) class EmailAdmin(admin.ModelAdmin): class Meta: model = EmailModel *****View.py****** def send_email(): email = EmailMessage( 'Title', ('abc', 'abc@gmail.com', '123123123'), 'abc@gmail.com', ['abc@gmail.com'] ) email.attach_file(EmailViewSet.upload_file) email.send() class EmailViewSet(viewsets.ModelViewSet): queryset = EmailModel.objects.all() serializer_class = EmailSerializer def create(self, request, *args, **kwargs): send_mail(' Test Subject here', 'Test here is the message.', 'abc@gmail.com', ['abc@gmail.com'], fail_silently=False) response = super(EmailViewSet, self).create(request, *args, **kwargs) send_email() # sending mail data = [{'location': request.data.get('location'), 'image': file} for file in request.FILES.getlist('image')] serializer = self.get_serializer(data=data, many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) message = EmailMessage(subject='Applicant data', body='PFA', from_email='abc@gmail.com', to='abc@gmail.com', bcc='abc@gmail.com', connection=None, attachments=data, headers=self.data, cc='abc@gmail.com', reply_to=None) # Attach file # with open(attachment, 'rb') as file: # message.attachments = [ # (attachment, file.read(), 'application/pdf') # ] return response, message.send(), Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) *****Serializer.py****** class EmailSerializer(serializers.ModelSerializer): class Meta: model = EmailModel fields = ('upload_file',) ******settings.py****** EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey' EMAIL_HOST_PASSWORD = 'here i am using my sendgrid api … -
CreateView form is not "rendering" in a template tag
Setup I have successfully setup a CreateView class that allows user to create a Journal. You only have to enter the name and press the "Add" button. views.py ... class CreateToJournal(LoginRequiredMixin, CreateView): model = to_journal template_name = 'to_journals/to_journal_list.html' fields = ('journal_name',) def get_success_url(self): return reverse('to-journals') def form_valid(self, form): form.instance.journal_user = self.request.user return super(CreateToJournal, self).form_valid(form) def get_context_data(self, **kwargs): context = super(CreateToJournal, self).get_context_data(**kwargs) context['to_journals'] = to_journal.objects.filter(journal_user=self.request.user) return context ... to_journal_list.html ... <form class="" id="myForm" action="" method="post"> {% csrf_token %} {{ form }} <button type="submit" id="add-button">Add</button> </form> ... This creates a new Journal and reloads the page to reflect the changes made. I am now trying to move the whole Journal creation process to the "home" page, using a template tag. Mostly it works fine and renders all user journals on the home page, but there is a problem with form rendering. Problem The new template tag does not render the form created by CreateView. The input field is not displayed here on the page with a template tag. I couldn't find any specific information (or general, for that matter) regarding the relationship between forms and templatetags. My setup for the template tag is the following: ... ├───pages │ └───templatetags │ └───__init__.py │ … -
Read multiple rows of a column from an excel sheet and save it as a dictionary
someone please help me with these 2 questions, am new to python language! I have an excel file with columns as Bank Name, About, Products, Popular Products, Loans, Insurance, Cards and Banking. Final Updated Banksheet what i have done is read the excel file and updated its value to my database but the format in which i want my databse to look like for Product type should be something like this: {"'Account':['Savings','Current'], 'Loan':['Consumer Loan','Personal Loan','Housing Loan','Vehicle Loan','MSME Loan'], 'Maha eTrade Online Share Trading':None, 'Maha Mobile Banking':None, 'Internet Banking':None} but currently my data in database is populating like this: {"{'Account':['Savings','Current']}","{'Loan':['Consumer Loan','Personal Loan','Housing Loan','Vehicle Loan','MSME Loan']}","Maha eTrade Online Share Trading","Maha Mobile Banking","Internet Banking"} Here is my Code: def update_bank_data(): from loans.models import BankData filename = 'filecontainer/ifscdata/Final Updated Banksheet.xlsx' exist =0 if os.path.isfile(filename): print("file exists") exist = 1 if exist: xl_workbook = xlrd.open_workbook(filename) print("------------new file=-----------------------") print(filename) sheet_names = xl_workbook.sheet_names() print('Sheet Names', sheet_names) j = 1 for sheet in sheet_names: xl_sheet = xl_workbook.sheet_by_name(sheet) no_of_row = xl_sheet.nrows + j print no_of_row next_bank_row_num=None currnt_bank_row_num=None j=1 try: while (j < no_of_row): if next_bank_row_num: currnt_bank_row_num = next_bank_row_num print("current bank----->", xl_sheet.cell_value(currnt_bank_row_num, 0)) else: currnt_bank_row_num = j print("current bank----->", xl_sheet.cell_value(currnt_bank_row_num, 0)) j = j + 1 while (xl_sheet.cell_value(j, 0) == … -
get ibject id with kwargs in drf
I have hardcoded one object that is wrong in my case. But I am facing some problems with solving this issue. I have a model looks like this class ProductCategory(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) is_top = models.BooleanField(default=False) class Cart(models.Model): product = models.ForeignKey(Product, related_name='product') size = models.ForeignKey(Size, related_name='size') count = models.IntegerField() order = models.ForeignKey(Order, blank=True, null=True, related_name='cart_items') is_free = models.BooleanField(default=False) and I have method: def transaction_saver(sender, instance, **kwargs): if kwargs['created']: cafe = instance.order.cafe order = instance.order order.state = Order.PAID order.save() customer = order.customer # name = ProductCategory.objects.get(category_id=kwargs.get('name')) total_count = order.cart_items.filter(is_free=False, product__category__name='Coffee/Tea').aggregate(Sum('count')) if total_count['count__sum'] is not None: count__sum = int(total_count['count__sum']) project_modules.point_free_item_calculation(cafe=cafe, client=customer, count=count__sum) clearly, here I have a product category that is named like 'Coffee/Tea' in this category I have many products. Now when customer buys a product from this category it should give one point to that user. But I have hardcoded this product__category__name='Coffee/Tea'. Unfortunately, it is wrong because I do not have only this category I have also other categories and to give point for other categories I cannot always change the code I should make it automate. How can I solve this problems? Any help please? Thank you in advance! -
Connection Django to MySql
I've created a new database. After that I created a new user and password CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'new_password'; then to grant all access to the database GRANT ALL ON my_db.* TO 'new_user'@'localhost'; FLUSH PRIVILEGES; But then I run python manage.py runserver I got File "/home/y700/Env/pro/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 166, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1044, "Access denied for user 'new_user'@'localhost' to database 'my_db'") What am I doing wrong? -
Pre-loader won't register on refresh
I am using Python and Django to modify a website, I'm using bootstrap 4 as well. I am attempting to change the preloaded currently in use (the typical circle spinner). I have entered the preloader within my html file, my css file, and made a custom.js file to support the loader yet when I refresh the page the loader shows the standard circle. (I have deleted the previous spinner files and style code but for some reason it still shows when I use "div id=preloader" Here is my preloader css style. #preloader { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: #f5f5f5; /* change if the mask should be a color other than white */ z-index: 1000; /* makes sure it stays on top */ } .pre-container { position: absolute; left: 50%; top: 50%; bottom: auto; right: auto; -webkit-transform: translateX(-50%) translateY(-50%); transform: translateX(-50%) translateY(-50%); text-align: center; } .spinner { width: 40px; height: 40px; position: relative; margin: 100px auto; } .double-bounce1, .double-bounce2 { width: 100%; height: 100%; border-radius: 50%; background-color: #53dd6c; opacity: 0.6; position: absolute; top: 0; left: 0; -webkit-animation: bounce 2.0s infinite ease-in-out; animation: bounce 2.0s infinite ease-in-out; } .double-bounce2 { -webkit-animation-delay: -1.0s; animation-delay: -1.0s; } @-webkit-keyframes … -
__init__() takes 1 positional argument but 2 were given: Multiple Inheritance
PLEASE READ THE QUESTION FIRST BEFORE MARKING IT AS DUPLICATE! This question is asked by many but almost all gave the same solution which I am already applying. So I have classes TestCase,B,C & D. Classes B & C inherit class TestCase & class D inherits both B & C. When I ran my code, class D was only running with methods for class B and ignoring C all along. Then I found this answer regarding multiple inheritance and tried to apply it in my code. Now my classes go like these from django.test import TestCase class B(TestCase): def __init__(self): super(B, self).__init__() class C(TestCase): def __init__(self): super(C, self).__init__() class D(B, C): def __init__(self): super(D, self).__init__() But when I try to run it, it says TypeError: __init__() takes 1 positional argument but 2 were given Why is it happening? How to fix this? Is the answer I am following right? Will this fix make D run for both B & C? This seems like a Python question mainly but tagging django too as TestCase class might have something to do with it.